【问题标题】:C++ ifstream error using string as opening file path.使用字符串作为打开文件路径的 C++ ifstream 错误。
【发布时间】:2011-09-13 11:54:25
【问题描述】:

我有:

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错误。
  • 这仍然非常模糊。你不能让它真正描述具体的问题吗?

标签: c++ ifstream


【解决方案1】:

改变

ifstream file(filename);

ifstream file(filename.c_str());

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

【讨论】:

  • “爱”c++!
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 虽然你的答案是正确的,但它已经出现在接受的答案中,虽然不是很清楚:not a string pre-C++11.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    相关资源
    最近更新 更多