Filename Question

I'm wondering if you can have a string determine a file name. If so, please show me a code example.
You can, it is explained on this website.

You should take a look and read the whole thing. It talks about cin, cout, getline and iostream. It takes about writing to files which is the ofstream and the ifstream, so if you don't know what I am talking about it might be better to learn about it in the tutorial so that the website link makes sense :) If you already think you know your stuff then go right for it :).

This is the example they used as well,

Variables as file names

The file name in an open function is a C-style string. Because of the peculiarities of C++, you can't use a variable of type string as the parameter. However, if filename is a variable of type string, you can obtain the corresponding C-style string by calling the function filename.c_str(), and you can use this function call as a parameter to open. This makes it possible, for example, to get the name of a file from the user:


                string filename;
                ifstream datafile;
                cout << "Please enter the input file name: ";
                cin >> filename;
       filename.c_str() );

The open functions talks about opening a file to either read or to write. Which is in the tutorial talking about writing to files using the fstream class.
Thank you, great source!
Also note that with the current C++ standard you shouldn't need to use the c_str() method when calling open. You can now just use the std::string as the parameter.
Last edited on
Topic archived. No new replies allowed.