【问题标题】:opening a file based on user input c++根据用户输入c ++打开文件
【发布时间】:2017-02-03 13:57:28
【问题描述】:

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

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

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

【问题讨论】:

  • 查看std::ifstream的文档。
  • ... 并改用std::ofstream

标签: c++ file io user-input


【解决方案1】:

您的代码有几个问题。首先,如果要写入文件,请使用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;
}

【讨论】:

    【解决方案2】:

    您不能写信给ifstream,因为那是为了输入。你想写入一个ofstream,它是一个输出文件流。

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

    【讨论】:

    • 它仍然给我这个错误 [错误] no matching function for call to 'std::basic_ofstream::basic_ofstream(std::string&)'
    • @Hillman 我的错误,std::ofstream 的构造函数使用了const char* 而不是std::string,所以请从你的文件名中调用.c_str()
    猜你喜欢
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多