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

标签 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);

我不知道是什么问题。 name 是一个 string var,它是 fout 对象的预期输入。

最佳答案

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

关于c++ - 无法使用 Fout 创建和命名具有用户输入名称的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47987631/

相关文章:

c - 使用 "fgetc"提前发送 EOF

c++ - 将 GSL 与 Xcode 集成

c++ - 使用 openssl 在 C++ 中验证 RSA 签名

java - 使用 .. 父目录说明符 ("dot dot"解析路径名)而不解析符号链接(symbolic link)

java - 将不规则文件读入二维数组 - 打印 - 并找到列的平均值

c++ - 有效地将一个标准流复制到另一个标准流

javascript - 使用 Highland.js 的异步 map

c++ - 重定向有回调函数吗?

c++ - MJPEG 流无法在 OpenCV 2.4 中打开

python - 为什么我的 Python 脚本没有将最后几行写入我的文件?