【问题标题】:Not Able to Use Fout to Create and Name a file with a User Inputted Name无法使用 Fout 创建和命名具有用户输入名称的文件
【发布时间】:2018-06-07 19:55:26
【问题描述】:

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


【解决方案1】:

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

【讨论】:

  • 完美,谢谢。现在我明白了为什么这样的事情:ofstream fout ("test");有效,因为字符串文字被转换为 c 字符串。字符串变量并非如此。
【解决方案2】:

仅在 C++11 中引入了从 std::string 构造 std::ifstreamstd::ofstream 对象的能力。

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

ofstream fout(name);

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

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

ofstream fout(name.c_str());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2011-10-17
    • 2021-07-09
    • 2022-12-05
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多