C++ file name loop

Borland Delphi 2009 professional & c++bu...
February 16, 2010 at 11:24:00
Specs: Windows 7
This is a homework assignment. For part of my assignment I have to ask the user for a file
name (contains spaces) and then test to see if the file is valid if not loop it and ask the user if they want to enter in a different file name. If they don't, exit, if they do test it again to see if it is valid.

Below is my code for that part of the program. The loop created will not let the user re-enter a file name. I could use some help in figuring out how to fix it.

Thanks,

cout << "Please enter the file name including the file extension
for this \n"
<< "years rainfall: ";
getline(cin, ActFileName); //get file name

ActFin.open(ActFileName.c_str());

while(ActFin.fail()) //test file
{
// if file failed ask the user if they want to try again
cout << "File name is invalid. Would you like to enter another file name?"
<<" 'y' or 'n' \n";
cin >> yn;

if (yn == 'y')
//If user wants to re-enter file name ask and get the new file name
{
ActFin.clear();
cout << "Plese re-enter the file name for this years rainfall: \n";
getline(cin, ActFileName);
ActFin.open(ActFileName.c_str());
}
else //if user says no, exit
{
exit(0);
}

}


See More: C++ file name loop

Report •


#1
February 16, 2010 at 13:08:23
cin >> yn;
getline(cin, ActFileName);

The problem is cin >> char leaves a \n in the buffer, which getline() picks up.

The solution is to #include <limits>, then, assuming you're already using namespace std;, add the following before your getline():

cin.ignore(numeric_limits<streamsize>::max(),'\n');


Report •

#2
February 16, 2010 at 15:50:13
Thank you for your help Razor2.3. That makes sense and it worked.

Report •
Related Solutions


Ask Question