I need a user to enter 3 integers that will be used in some math formulas later on. However, I need to make sure the user only enters integers, not strings. I have read the other posts about C++ integer input validation, but it seems like a lot of unnecessary work to check for std::cin.fail() and clearing the buffer. Is there no way to simply throw an exception like in Java with the IOMismatchException? that I can catch and handle?
Asked
Active
Viewed 32 times
0
-
1If you've found some good example code for validating integer input from `std::cin`, why not put that in its own class and have it throw some special `IOMismatchException` you create. Then all your "unnecessary work" is separate in your project so you don't have to look at it or touch it as long as it works. – scohe001 Feb 17 '21 at 21:49
-
Perhaps I am looking for too easy of a way out, but that still involves using cin.fail(). I want to avoid that all together if possible. – The_Redhawk Feb 17 '21 at 21:52
-
You can tell the I/O stream to throw an exception for categories of problems: https://en.cppreference.com/w/cpp/io/basic_ios/exceptions – Eljay Feb 17 '21 at 21:53
-
I'll give that a look @Eljay – The_Redhawk Feb 17 '21 at 21:55
-
What is wrong with `if ( !(cin >> n) )...`? – zdf Feb 17 '21 at 21:56
-
Exceptions are slow, but if you have to wait for some pathetic meatbag to type the input in, why not throw exceptions? – user4581301 Feb 17 '21 at 21:58
-
If ( !(cin >>n) ) is giving me trouble. Also, what if I need the user to enter 20 integers, I need to write 20 if statements? – The_Redhawk Feb 17 '21 at 22:07
-
If you need to take in 20 numbers, you write a function and call it 20 times or if you're doing all the reading at once, you write a loop that iterates 20 times. Repeating code is for suckers, and a major cause of errors since every duplicate is an opportunity to introduce a bug or forget to fix a bug found in another copy.. – user4581301 Feb 18 '21 at 17:53
-
Good point. I had to put it on the back burner but I plan on attacking it again Friday – The_Redhawk Feb 19 '21 at 01:58
-
I created a function that checked the input with cin.good(). Got points deducted for too complicated a loop. – The_Redhawk Feb 22 '21 at 21:31