Using ifstream with variables

Hi Programmers,

I am creating an encryption program that encrypts whatever word doc you want. However, ifstream seems to only take constants (or does it?) I want the user to type their file name and then ifstream will read it. For example:

string userFile;

cin >> userFile;

ifstream theFileIwantToEncrypt(userFile);

That does not work. Only this works:

ifstream theFileIwantToEncrypt("theFile.txt")

(Note: This is not an entire program, just a small snippet.)

Basically, I want the user to be able to enter a file name and ifstream will read it. Thank you!
For some reason the ifstream constructor only accepts c-strings (const char*). To get a c string from a std::string you can use the c_str member function.
ifstream theFileIwantToEncrypt(userFile.c_str());

This has changed in C++11 so your code should work fine if compiled in C++11. Unfortunately not all compilers support this yet and you might have to pass additional flags to turn on C++11 mode.
cout << "Wow thanks for the quick reply and useful information!!!" << endl;
Topic archived. No new replies allowed.