C++ ifstream错误使用字符串作为打开文件路径.

Mar*_*ark 69 c++ ifstream

我有:

string filename: 
ifstream file(filename);
Run Code Online (Sandbox Code Playgroud)

编译器抱怨ifstream文件和字符串之间没有匹配.我需要将文件名转换为某些内容吗?

这是错误:

error: no matching function for call to ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)’
/usr/include/c++/4.4/fstream:454: note: candidates are: std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]
Run Code Online (Sandbox Code Playgroud)

Set*_*gie 137

更改

ifstream file(filename);
Run Code Online (Sandbox Code Playgroud)

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

因为一个构造函数ifstream需要一个const char*,而不是一个string前C++ 11.

  • 非常“爱”c++! (2认同)

Ale*_*ler 12

ifstream构造函数需要一个const char*,所以你需要做的ifstream file(filename.c_str());,使其工作.