How to open a variable filename with ifstream

In a new and supposedly improved version of a scheduler program I am working on, I have encountered a problem: I need to open a file specified by the user. How can I get ifstream to accept a string variable as a filename?
1
2
3
std::string file_name = "my_file_name.txt";

std::ifstream ifs(file_name.c_str());
That worked, thanks.
Mayby not, when I use "ifs" for the ifstream and "file_name" for the file name it works fine, but when I change them around it doesn't.

Example:

string month;
string data [31];

cout << "Please enter a month" << endl;
cin >> month;

ifstream input(month.c_str());
for (int i = 1; i < 31; i++)
{
getline(input, data[i]);
cout << i;
cout << data[i] << endl;
}

input.close ( );

What am I doing wrong?
Also, can you use this same code for ofstream, or does that require something compleatly diffrent?
Last edited on
That looks like it should work. As long as you only type in a one word name when it asks you for month. Can you explain what exactly is going wrong?

And yes, its the same for ofstream;
Found the problem: I'm an idiot.

forgot to include the fstream library.

Everything works fine now.
Topic archived. No new replies allowed.