This is an extract from a much bigger program:
What I want to do, is to ask user for a file name which they want to read all the lines from, and do some operations at one of the lines at a time. Also, if the user specifies a file name that does not exist, I want the program to ask for the file name again.Code:#include <fstream> #include <iostream> #include <string> using namespace std; int main() { ifstream input; bool invalid; string message, infile; invalid = false; do { if(invalid == true) { cout << "The " << infile << " does not exist. Please specify another file name." << endl; } invalid = true; cout << "What is the name of the file you want to read from?" << endl; cin >> infile; input.open(infile.c_str()); }while(input.is_open() == false); while(input.eof() == false) { getline(input, message); //do crazy irrelevant stuff with 'message' string } }
In my program, when the user specifies a correct file name at the first time, everything works. However, if they input a wrong name at least once and eventually a correct one, the getline() function does not read anything!! It just returns an empty string into the 'message' and additionally, the last while loop is infinite.
What the hell? How can I make it work?
Edit:
I am using Visual Studio 2008. My friend with code::blocks compiled the code above and it works for him. Can it be a compiler bug? How to fix it then?