使用字符串作为打开文件路径的 ifstream 错误。

我有:

string filename:
ifstream file(filename);

编译器抱怨 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>]
94209 次浏览

ifstream构造函数需要一个 const char*,因此您需要执行 ifstream file(filename.c_str());来使其工作。

改变

ifstream file(filename);

ifstream file(filename.c_str());

因为 ifstream的构造函数采用 const char*,而不是 string pre-C + + 11。

在 c + +-11中,它也可以是一个 std: : string。因此(安装 c + +-11和)将您项目的方言改为 c + +-11也可以解决这个问题。