#include <iostream>
#include <fstream>
usingnamespace std;
int main () {
char YesNo;
char iFileNam[80], oFileNam[80];
do {
cout << "Enter the name of file to open: ";
gets(iFileNam);
cout << "The file is: " << iFileNam << endl;
cout << "Enter the name of file to write: ";
gets(oFileNam);
cout << "The file is: " << oFileNam << endl;
cout << "Do you want to continue?Y/N: ";
cin >> YesNo;
}
while(YesNo == 'Y' | YesNo == 'y');
return 0;
}
When I use the above code to run the file till the user wants, it wont let me input the name of the first file in the second run. Any reason? How can I correct it?
#include <iostream>
#include <fstream>
usingnamespace std;
int main () {
char YesNo;
string iFileNam, oFileNam; // it's a good idea to use strings instead of char arrays
do {
cout << "Enter the name of file to open: ";
getline(cin,iFileNam); // As Athar suggested
cout << "The file is: " << iFileNam << endl;
cout << "Enter the name of file to write: ";
getline(cin,oFileNam);
cout << "The file is: " << oFileNam << endl;
cout << "Do you want to continue?Y/N: ";
cin >> YesNo;
cin.sync(); // !!!
}
while(YesNo == 'Y' || YesNo == 'y');
return 0;
}
cin.sync() doesn't reliably solve the problem (doesn't change anything for me).
Since YesNo is a single char, the terminating new line will be left in the input stream.
You can either use cin.ignore to discard it or make YesNo a string and use getline here as well.
This is a better solution. This question has been asked and answered about a thousand times. The problem is that the extraction technique of getline and gets is totally different from that of cin. cin does not read past the '\n' so the next iteration reads a blank line automatically. Also check the article database as there are a couple of articles on this. http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.6
the cin::synch function does seem to work for me as well but it is vaguely described by the standard and reference material that I have found which makes me wonder whether it will work in all cases. I think that the ignore function is described more clearly and is also more versatile since you can specify other delimiters as well. It just so happens that most of the time you are dealing with the '\n' issue.