关于使用字符串作为参数的c ++:ifstream :: open()函数

ifstream::open() function using a string as the parameter

本问题已经有最佳答案,请猛点这里访问。

我正在尝试制作一个程序,要求他们用户要读取的文件,当我尝试myfile.open(fileName)时,出现错误:在该行出现"没有匹配的函数来调用std::basic_ifstream >::open(std::string&)'"。

1
2
3
4
5
6
string filename;
cout<<"Enter name of file:";
cin>>filename;
ifstream myFile;
myFile.open(filename); //where the error occurs.
myFile.close();


在早期版本的C ++(C ++ 03)中,open()仅将const char *用作第一个参数,而不是std::string。 正确的调用方式是:

1
myFile.open(filename.c_str());

但是,在当前的C ++(C ++ 11)中,该代码很好,因此请查看是否可以告诉编译器启用对此代码的支持。