编译错误:ifstream :: open只接受引号中的字符串值“"而不是字符串变量 [英] compile error: ifstream::open only accepts string values in quotes "" and not string variables

查看:740
本文介绍了编译错误:ifstream :: open只接受引号中的字符串值“"而不是字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


<$ p $ open 函数对于传入的字符串值有什么限制? $ p> ifstream文件;
string filename =output.txt;
file.open(filename);

我尝试将字符串值传递给字符串变量,但是当它尝试编译时,结果...

  agent.cpp:2:20:error:ofstream:没有这样的文件或目录
agent .cpp:在函数'std :: string readingline(std :: string)'中:
agent.cpp:11:错误:聚集'std :: ifstream文件'具有不完整的类型,无法定义
agent.cpp:在函数'int main()'中:
agent.cpp:44:错误:集合'std :: ofstream writefile'具有不完整类型,无法定义

另一方面,当我只是在像filename.txt这样的引号中传递一个字符串值时,它编译得很好,运行正常。

  ifstream文件; 
file.open(output.txt);

为什么会这样?

有没有一种方法可以解决这个问题?

可悲的是,这是如何构造和打开 std::( i | o)fstream 由标准定义。使用 file.open(filename.c_str())



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


Does open function have some sort of restriction as to what kind of string value is passed in?

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

I tried to pass a string value with a string variable, but when it tries to compile, the result is...

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

On the other hand, when I just pass a string value in quotes like "filename.txt" , it compile fine and runs fine.

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

Why is this the case?

Is there a way to solve this problem?

解决方案

Sadly, this is how the constructor and open of std::(i|o)fstream are defined by the standard. Use file.open(filename.c_str()).

Some standard libraries provide an extension that allows std::string as a parameter, e.g. Visual Studio.

这篇关于编译错误:ifstream :: open只接受引号中的字符串值“&quot;而不是字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆