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

时间:2017-12-27 06:47:41

标签: c++ file stream output outputstream

我做了一个小程序,让用户输入文件名,然后是程序创建一个带有该名称的.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);

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

2 个答案:

答案 0 :(得分:2)

传递name.c_str(),ofstream没有一个带std :: string的构造函数,只有char const *,并且没有从std :: string到char指针的自动转换;

答案 1 :(得分:1)

std::ifstream构建std::ofstreamstd::string对象的能力仅在C ++ 11中引入。

如果编译器具有针对C ++ 11标准进行编译的选项,请启用该选项。如果你这样做,你应该可以使用

ofstream fout(name);

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

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

ofstream fout(name.c_str());
相关问题