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

C++ ifstream error using string as opening file path.

本文关键字:路径 文件 C++ifstream 错误 字符串      更新时间:2023-10-16

我有:

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

更改

ifstream file(filename);

ifstream file(filename.c_str());

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

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

在c++-11中,它也可以是std::字符串。因此(安装c++-11并)将项目的方言更改为c++-11也可以解决这个问题。