Jack F
Jack F

Reputation: 553

prompting the user for a file to save data in

what i want to do is to prompt the user for a file to save the data in what i have tried is :

  string save;
  cout<<"Enter filename to save (ex: file.txt): ";
  cin>>save;
  ofstream myfile;
  myfile.open(save);
  myfile <<"ID \tName \tSales\n";

however i get an error: no matching function for call to ‘std::basic_ofstream >::open(std::string&)’

EDIT:

So i have updated my code but this doesn't allow me to enter the name of the file. why is that

  char file_name[81];
  cout<<"Enter filename to save (ex: file.txt): ";
fflush(stdin);
  cin.getline(file_name, 81);

Upvotes: 0

Views: 1015

Answers (4)

wintermute
wintermute

Reputation: 55

The constructor is explicit and expects a variable of type const char *, therefore you'll have to pass save.c_str(), which returns a const char * for the string object.

Upvotes: 1

Sebastian
Sebastian

Reputation: 1889

Instead of

cin >> filename;

which stops after the first token, you should probably use

getline(cin, filename);

so you can input filenames with spaces.

Also, consider to use argv (and maybe some library for option parsing).

Upvotes: 1

Neil Sainsbury
Neil Sainsbury

Reputation: 1460

Here is a simple program demonstrating what you want to do:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string filename;
    cout << "Enter filename to save (eg. file.txt): ";
    cin >> filename;

    ofstream myfile;
    myfile.open(filename.c_str());
    myfile << "ID \tName\tSales" << endl;
    myfile.close();

    return 0;
}

Upvotes: 0

Jesse Good
Jesse Good

Reputation: 52365

There is no constructor or open function taking an std::string in C++03: myfile.open(save.c_str());. However, they added them in C++11.

Here is a nice reference. Notice the since C++11 note next to the std::string version.

Upvotes: 3

Related Questions