【问题标题】:compile error: ifstream::open only accepts string values in quotes "" and not string variables编译错误:ifstream::open 只接受引号 "" 中的字符串值,而不接受字符串变量
【发布时间】:2011-12-18 03:47:51
【问题描述】:

open 函数是否对传入的字符串值有某种限制?

ifstream file;
string filename = "output.txt";
file.open(filename);

我试图用字符串变量传递一个字符串值,但是当它尝试编译时,结果是……

agent.cpp:2:20: error: ofstream: No such file or directory
agent.cpp: In function ‘std::string readingline(std::string)’:
agent.cpp:11: error: aggregate ‘std::ifstream file’ has incomplete type and cannot be     defined
agent.cpp: In function ‘int main()’:
agent.cpp:44: error: aggregate ‘std::ofstream writefile’ has incomplete type and cannot be defined

另一方面,当我只在 "filename.txt" 之类的引号中传递一个字符串值时,它可以正常编译并运行。

ifstream file;
file.open("output.txt");

为什么会这样?

有没有办法解决这个问题?

【问题讨论】:

标签: c++ g++ fstream ifstream


【解决方案1】:

遗憾的是,这就是标准定义std::(i|o)fstream 的构造函数和open 的方式。使用file.open(filename.c_str())

一些标准库提供了允许std::string 作为参数的扩展,例如视觉工作室。

【讨论】:

  • 谢谢 Xeo。使用file.open(filename.c_str()) 成功了。
  • 不再是扩展,而是符合C++11标准。
  • @Bo:等等,我们在 C++11 中找到了那些?我一定错过了。 浏览标准
  • 我想const char*std::string 更受青睐的原因是(POSIX)定义的文件名永远不能包含嵌入的空值。说 file.open(fname.c_str()) 会让程序员明白这一点
【解决方案2】:

通过包含fstream 并传递filename.c_str() 而不仅仅是filename,我解决了这个问题。

关于类型不完整的消息是因为您缺少标题(可能无论如何,您没有显示完整的示例)。

open 采用 c 风格的字符串,而不是 string 类。

【讨论】:

    【解决方案3】:

    我认为您的错误消息可能与相关代码无关,但 open 采用 C 风格 const char* 而不是 C++ string。您需要在调用中使用filename.c_str() 才能使其正常工作。

    【讨论】:

    • 感谢 Mark B 的建议。
    猜你喜欢
    • 2013-05-25
    • 2015-07-02
    • 2013-12-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    相关资源
    最近更新 更多