使用字符串作为打开文件路径的C ++ 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>]
    
已邀请:
        更改
ifstream file(filename);
ifstream file(filename.c_str());
因为
ifstream
的构造函数需要
const char*
,而不是
string
C ++ 11之前的版本。     
        
ifstream
构造函数期望
const char*
,因此您需要执行
ifstream file(filename.c_str());
使其生效。     
        在c ++-11中,它也可以是std :: string。因此(安装c ++-11并将项目的方言更改为c ++-11)也可以解决此问题。     

要回复问题请先登录注册