c++ - 编译错误:ifstream::open 只接受引号 ""中的字符串值而不接受字符串变量

标签 c++ g++ fstream ifstream

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");

为什么会这样?

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

最佳答案

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

一些标准库提供了一个扩展,允许将 std::string 作为参数,例如 Visual Studio 。

关于c++ - 编译错误:ifstream::open 只接受引号 ""中的字符串值而不接受字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8549676/

相关文章:

c++ - 如何设置默认g++?

c++ - 只有在 header 中定义的函数才会被内联。我错过了什么吗?

c++ - 这个函数通过循环要求用户输入文件名的错误在哪里?

c++ - 从 .txt 文件中读取浮点类型数字并在公式中使用它们

c++ - 通过 fstream 读取文件时,损坏的数据存储在变量中……为什么?

c++ - 是否应该为类成员访问表达式中的依赖类/命名空间名称延迟名称查找?

c++ - 为所有 Linux 发行版编译 C++

c++ - 如何确定在 C++ 中添加到 vector 的值的数量?

c++ - 在 QString 中推送 QChar

c++ - 如何在 C++ 中手动读取 PNG 文件?