3

我正在学习 C++,当我尝试在ifstream方法中使用String时遇到了一些麻烦,如下所示:

string filename;
cout << "Enter the name of the file: ";
   cin >> filename;
ifstream file ( filename );

这是完整的代码:

// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;

int main ( int argc, char** argv )
{
    string file;
    long begin,end;
    cout << "Enter the name of the file: ";
       cin >> file;
    ifstream myfile ( file );
    begin = myfile.tellg();
    myfile.seekg (0, ios::end);
    end = myfile.tellg();
    myfile.close();
    cout << "File size is: " << (end-begin) << " Bytes.\n";

    return 0;
}

这是Eclipse的错误,方法前的x

no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)'

但是当我尝试在 Eclipse 中编译时,它会在方法前添加一个x,这表示语法错误,但语法有什么问题?谢谢!

4

2 回答 2

8

你应该传递char*ifstream构造函数,使用c_str()函数。

// includes !!!
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() 
{   
  string filename;
  cout << "Enter the name of the file: ";
  cin >> filename;
  ifstream file ( filename.c_str() );    // c_str !!!
}
于 2009-07-21T13:22:56.280 回答
5

问题是 ifstream 的构造函数不接受字符串,而是 c 风格的字符串:

explicit ifstream::ifstream ( const char * filename, ios_base::openmode mode = ios_base::in );

并且std::string没有隐式转换为 c 样式字符串,而是显式转换:c_str().

采用:

...
ifstream myfile ( file.c_str() );
...
于 2009-07-21T13:31:49.093 回答