我制作了一个小程序,让用户输入文件名,然后程序创建一个具有该名称的 .doc 文件。然后,用户输入一些内容,它出现在 .doc 文件中:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
cout << "\nWhat do you want to name your file?\n\n";
string name = "";
char current = cin.get();
while (current != '\n')
{
name += current;
current = cin.get();
}
name += ".doc";
ofstream fout(name);
if (fout.fail())
{
cout << "\nFailed!\n";
}
cout << "Type something:\n\n";
string user_input = "";
char c = cin.get();
while (c != '\n')
{
user_input += c;
c = cin.get();
}
fout << user_input;
cout << "\n\nCheck your file system.\n\n";
}
我在创建文件的行收到错误:
ofstream fout(name);
我不知道是什么问题。 name
是一个 string
var,它是 fout
对象的预期输入。
最佳答案
通过name.c_str(),ofstream没有接受std::string的构造函数,只有char const *,并且没有std::string到char指针的自动转换;
关于c++ - 无法使用 Fout 创建和命名具有用户输入名称的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47987631/