I've been able to open text files, read them and write to them. However, I always have to specify the name of the file before I compile.
IE: ofstream myfile ("example.txt");

I've tried to declare a string, and then use that where the name of the file would nomally be, but I get the compiler error:
"no matching function for call to `std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::string&)"

My goal is to have a simple program where the user can input the name of the file they want to open.
Any help would be greatly appreciated.

string filename; //variable for the text file, such as: "example.txt"
cout << "What is the name of the text file?\n";
cin >> filename;
ofstream myfile (filename); //This is where the compiler error occurs
if (myfile.is_open())
  {
    myfile << "Example output.\n";
    myfile.close();
  }
else cout << "Unable to open file";

Thanks!

ofstream myfile (filename.c_str());

Gives you a C style string that the method wants (with a '\0' (null) terminus).

ofstream myfile (filename.c_str());

Gives you a C style string that the method wants (with a '\0' (null) terminus).

Thanks! It worked perfectly.

Opening a file requires a C-style character array, not a C++ string. Jonsca has posted your answer. I just thought I add why.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.