Inertial Ignorance
Inertial Ignorance

Reputation: 563

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

I made a little program that gets the user to enter the name of a file, followed by the program creating a .doc file with that name. Then, the user enters some input and it appears in the .doc file:

#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";
}

I'm receiving an error at the line where I create the file:

ofstream fout(name);

I can't figure out what the problem is. name is a string var, which is the intended input for a fout object.

Upvotes: 0

Views: 38

Answers (2)

R Sahu
R Sahu

Reputation: 206717

The ability to construct a std::ifstream and std::ofstream object from std::string was introduced only in C++11.

If your compiler has the option to compile against the C++11 standard, turn on that option. If you do that, you should be able to use

ofstream fout(name);

For example, if you are using g++, you can use the command line option -std=c++11.

If your compiler, does not support the C++11 standard, you will need to use

ofstream fout(name.c_str());

Upvotes: 1

SoronelHaetir
SoronelHaetir

Reputation: 15172

pass name.c_str(), ofstream does not have a constructor that takes a std::string, only char const *, and there is no automatic conversion from std::string to a char pointer;

Upvotes: 2

Related Questions