Hey guys, Just a quick question. How do you, personally, deal with a failed input stream and type checking input?
I use:
1 2 3 4 5 6 7 8 9
cout << "\n\nEnter a menu option: ";
while(!(cin >> menuGameMode))
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Enter a menu option: ";
}
To me this looks much easier to read without the nested while loops. Also, Not only do I think it is easier to read but it is great practice when you are working with other programmers. Suppose another programmer is using your code and something goes wrong, throwing an error can put him in a position to recover and better handle it because he might not know the implementation of your code and it will give him some information as to what is going on.
I am not a professional yet and I have little experience so you might be correct but that is just my two cents.
To me this looks much easier to read without the nested while loops.
My code reads a series of number pairs from a stream, skipping lines with an unexpected format. Yours attempts to read two numbers from the console. They aren't really comparable.
But, here's the equivalent of yours without exceptions:
while (in.good())
{
try {
int a, b;
in >> a >> b;
std::cout << a << " + " << b << " = " << a + b << '\n';
}
catch (std::istream::failure& ex)
{
if (in.fail())
{
try {
in.clear();
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
catch (std::istream::failure&)
{
}
}
}
}
}
Why did you do two try...catch statements there? You catch potential istream failure, then try to clear the input stream and then catch another potential istream failure.
Just wondering if that is a standard method of catching bad input through exceptions or if it was a typo or something else entirely.