根据用户输入c ++打开文件

Hil*_*man 1 c++ io user-input file

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

但是当我编译它时,它给了我这个错误:

[Error] no match for 'operator<<' (operand types are 'std::ifstream {aka std::basic_ifstream<char>}' and 'const char [7]')
Run Code Online (Sandbox Code Playgroud)

有谁知道如何解决这个问题?谢谢...

Don*_*uck 6

您的代码有几个问题.首先,如果要写入文件,请使用ofstream.ifstream仅用于读取文件.

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

fileC.open(filename.c_str());
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)