无法使用Fout创建和命名用户输入名称的文件

Not Able to Use Fout to Create and Name a file with a User Inputted Name

本文关键字:用户 输入 文件 Fout 创建      更新时间:2023-10-16

我制作了一个小程序,使用户输入文件的名称,然后是程序创建带有该名称的.doc文件的程序。然后,用户输入一些输入,并且显示在.doc文件中:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
   cout << "nWhat do you want to name your file?nn";
   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:nn";
   string user_input = "";
   char c = cin.get();
   while (c != 'n')
   {
      user_input += c;
      c = cin.get();
   }
   fout << user_input;
   cout << "nnCheck your file system.nn";
}

我在创建文件的线路上收到错误:

ofstream fout(name);

我无法弄清楚问题是什么。namestring VAR,它是fout对象的预期输入。

pass name.c_str(),ofStream没有一个构造函数,该构造函数符合std :: string,只有char const *,并且没有自动转换从std :: string到一个炭指针;

仅在C 11中引入了std::stringstd::ifstreamstd::ofstream对象的能力。

如果您的编译器可以选择针对C 11标准进行编译,请打开该选项。如果这样做,您应该能够使用

ofstream fout(name);

例如,如果您使用的是g++,则可以使用命令行选项-std=c++11

如果您的编译器不支持C 11标准,则需要使用

ofstream fout(name.c_str());