opening a file based on user input c++

做~自己de王妃 提交于 2021-02-11 08:01:54

问题


I am trying to make a program that would open a file based on the users input. Here`s my code:

#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;
}

But when I compile it, it gives me this error:

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

Does anyone know how to solve this? Thank you...


回答1:


Your code has several problems. First of all, if you want to write in a file, use ofstream. ifstream is only for reading files.

Second of all, the open method takes a char[], not a string. The usual way to store strings in C++ is by using string, but they can also be stored in arrays of chars. To convert a string to a char[], use the c_str() method:

fileC.open(filename.c_str());

The close method is a method, not an attribute, so you need parentheses: fileC.close().

So the correct code is the following:

#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;
}



回答2:


You cannot write to an ifstream because that is for input. You want to write to an ofstream which is an output file stream.

cout << "which file do you want to open?";
cin >> filename;

ofstream fileC(filename.c_str());
fileC << "lalala";
fileC.close();


来源:https://stackoverflow.com/questions/42025936/opening-a-file-based-on-user-input-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!