基于用户输入c++打开一个文件

opening a file based on user input c++

本文关键字:一个 文件 输入 于用户 用户 c++      更新时间:2023-10-16

我正在尝试制作一个程序,根据用户的输入打开一个文件。这是我的代码:

#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]')

有人知道怎么解决这个问题吗?非常感谢。

您的代码有几个问题。首先,如果要在文件中进行写入,请使用ofstreamifstream仅用于读取文件。

其次,open方法采用char[],而不是string。在C++中存储字符串的常用方法是使用string,但它们也可以存储在chars的数组中。要将string转换为char[],请使用c_str()方法:

fileC.open(filename.c_str());

close方法是一个方法,而不是属性,因此需要括号: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;
}

您不能写入ifstream,因为它用于输入。您想要写入ofstream,它是输出文件流。

cout << "which file do you want to open?";
cin >> filename;
ofstream fileC(filename.c_str());
fileC << "lalala";
fileC.close();
相关文章: