在ifstream方法中放置一个字符串

Nat*_*pos 3 c++ string file-io input ifstream

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

string filename;
cout << "Enter the name of the file: ";
   cin >> filename;
ifstream file ( filename );
Run Code Online (Sandbox Code Playgroud)

这是完整的代码:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

这里是Eclipse的错误,方法之前的x:

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

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

Kir*_*sky 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 !!!
}
Run Code Online (Sandbox Code Playgroud)


CsT*_*mas 5

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

explicit ifstream::ifstream ( const char * filename, ios_base::openmode mode = ios_base::in );
Run Code Online (Sandbox Code Playgroud)

std::string没有隐式转换为c风格的字符串,而是明确的一个:c_str().

使用:

...
ifstream myfile ( file.c_str() );
...
Run Code Online (Sandbox Code Playgroud)