My current project requires me to trap non-valid input (values that are not rational numbers) and return an error. The code I'm using is:
However, my instructor's code is this:Code:// Input the value while (cin.fail()) { cout << "Invalid value. Please enter a real number: "; cin.clear(); cin.ignore(1000, '\n'); // clean buffer cin >> values[element]; // Ask for proper input };
Would both be correct, and which would be better?Code:// Input the value char chrResponse; if (cin.rdstate() != 0) { cin.clear(); cin >> chrResponse; // clean buffer } // Ask for proper input