我正在尝试制作一个程序,该程序将根据用户输入打开文件。
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filename;
ifstream fileC;
cout<<"which file do you want to open?";
cin>>filename;
fileC.open(filename);
fileC<<"lalala";
fileC.close;
return 0;
}
但是当我编译它时,它给了我这个错误:
[Error] no match for 'operator<<' (operand types are 'std::ifstream {aka std::basic_ifstream<char>}' and 'const char [7]')
有谁知道如何解决这个问题?
谢谢...
您的代码有几个问题。首先,如果要写入文件,请使用ofstream
. ifstream
仅用于读取文件。
其次,open方法需要一个char[]
, not a string
。在 C++ 中存储字符串的常用方法是使用string
,但它们也可以存储在数组中char
s。要转换一个string
to a char[]
, 使用c_str()
method:
fileC.open(filename.c_str());
The close
method 是一个方法,而不是一个属性,所以你需要括号:fileC.close()
.
所以正确的代码如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filename;
ofstream fileC;
cout << "which file do you want to open?";
cin >> filename;
fileC.open(filename.c_str());
fileC << "lalala";
fileC.close();
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)