使用字符串作为打开文件路径的 C++ ifstream 错误。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6323619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ ifstream error using string as opening file path.
提问by Mark
I have:
我有:
string filename:
ifstream file(filename);
The compilers complains about no match between ifstream file and a string. Do I need to convert filename to something?
编译器抱怨 ifstream 文件和字符串之间不匹配。我需要将文件名转换为什么吗?
Here's the error:
这是错误:
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>]
回答by Seth Carnegie
Change
改变
ifstream file(filename);
to
到
ifstream file(filename.c_str());
Because the constructor for an ifstream
takes a const char*
, not a string
pre-C++11.
因为 an 的构造函数ifstream
需要一个const char*
,而不是一个string
pre-C++11。
回答by Alexander Gessler
The ifstream
constructor expects a const char*
, so you need to do ifstream file(filename.c_str());
to make it work.
该ifstream
构造函数需要一个const char*
,所以你需要做的ifstream file(filename.c_str());
,以使其正常工作。
回答by evi v
in c++-11 it can also be an std::string. So (installing c++-11 and) changing the dialect of you project to c++-11 could also fix the problem.
在 c++-11 中,它也可以是 std::string。因此(安装 c++-11 和)将项目的方言更改为 c++-11 也可以解决问题。