C++中使用字符串作为文件路径打开ifstream时出现错误。

72

我有:

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>]

1
我相信你可以改善这个问题的标题。 - Lightness Races in Orbit
我将其更改为 ifstream 错误。 - Mark
那仍然非常模糊。你不能让它真正描述具体的问题吗? - Lightness Races in Orbit
3个回答

144

更改

ifstream file(filename);

ifstream file(filename.c_str());

在C++11之前,ifstream的构造函数需要一个const char*参数而不是string


2
非常热爱C++! - MajesticRa

11

ifstream 构造函数需要一个 const char*,所以你需要做 ifstream file(filename.c_str()); 才能让它工作。


1
在C++11中,它也可以是std::string。因此(安装C++11并)将您的项目语言设置为C++11也可能解决问题。

1
虽然你的答案是正确的,但已经在被接受的答案中提到了,只是没有那么清楚:在 C++11 之前不是字符串。 - Chris Maes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接