如何根据用户输入指定的文件名打开文件?

时间:2017-02-09 22:07:27

标签: c++ fstream

我想创建一个简单的程序,允许用户创建/打开文件并向其中添加文本。这是我目前的代码:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    cout << "Enter file name:" << endl;
    char fileName;
    cin >> fileName;
    ofstream myFile;
    myFile.open(fileName, ios::out);
    myFile << "This is the file text.\n";
    myFile.close();
    return 0;
}

我在myFile.open(fileName, ios::out)收到以下错误:

  

错误:没有匹配函数来调用'std :: basic_ofstream&lt; char&gt; :: open(std :: __ cxx11 :: string&amp;,const openmode&amp;)'

2 个答案:

答案 0 :(得分:2)

您遇到的一个简单问题是存储文件名的变量filename的类型为char。将其更改为string,以便它可以正常工作。

另一方面,请尝试分解您收到的错误消息:

  

no matching function for call to 'std::basic_ofstream::open(std::__cxx11::string&, const openmode&)'

open(std::__cxx11::string& ...中,它明确指出文件名的数据类型应为string&。这表示您遇到了数据类型错误,这是因为您使用了char而不是string

另一件事:只有当你想接受一个字母作为输入时才使用char;当你想要一个单词或一个句子时,将它存储在一个字符串变量中,并使用getline()函数从用户那里获取它。这将使您的生活更轻松。

要修改代码,首先将变量声明语句更改为:

    string fileName; // std:: is not required as you have the line "using namespace std"

其次,将文件名的输入语句从cin >> filename;更改为:

    getline(cin, fileName);

它应该在这些变化之后起作用。

编辑:我找到了问题的问题。你将把open命令更改为:

myFile.open(fileName.c_str(), ios::out);

就像在错误中所说的那样,函数需要传递给ot的字符串,但是,当我们将字符串作为输入并将其存储在变量fileName中时,它只是将字符串转换为const char *。当您运行代码时,这是不可见的,但每隔一段时间,它就会导致错误。

这应该现在肯定有效。

答案 1 :(得分:1)

如果您查看错误消息,则打开括号中的前半部分会告诉您答案。用户正在键入char,文件名应该是一个字符串。而不是:

char fileName;

使用:

string fileName;
相关问题