My C++ professor is adamant that when checking for input failure, one must use separate while()
loops for each individual input. He indicated that the following method of checking more than one input gathered in a single cin
statement would not work:
while (!good){
cout << "Enter the length and the width of the rectangle: ";
cin >> length >> width;
if(!cin){
cout << "Bad input, try again" << endl;
cin.clear();
cin.ignore(200, '\n');}
else {
good = true;}}
His proposed method:
bool good = false;
while (!good){
cout << "Enter the length rectangle: ";
cin >> length;
if(!cin){
cout << "Bad input, try again" << endl;
cin.clear();
cin.ignore(200, '\n');}
else {
good = true;}}
while (good){
cout << "Enter the width rectangle: ";
cin >> width;
if(!cin){
cout << "Bad input, try again" << endl;
cin.clear();
cin.ignore(200, '\n');}
else {
good = false;}}
My method above seems to work just fine. If non-numerical characters are inputted for either of the inputs, the loop will prompt for new input and clear the fail-state.
Is it simply considered bad form to check for input failure as I have done? I'm hoping to learn more clearly why my method is erroneous. If my method is faulty, is there a way to check for input failure without using separate loops for every single user-input? I mainly ask because I'm writing a program that involves getting many inputs from a file, and individually checking each variable seems overly tedious. I'm thinking there must be a better way.