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

问题描述 投票:0回答:2

我做了一个小程序,让用户输入文件的名称,然后程序创建一个具有该名称的.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对象的预期输入。

c++ file stream output outputstream
2个回答
2
投票

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


1
投票

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

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

ofstream fout(name);

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

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

ofstream fout(name.c_str());
© www.soinside.com 2019 - 2024. All rights reserved.