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/