| sirjames2004 (3) | |||||
Hey guys. I'm having some trouble with input validation for one of my assignments in my Advanced C++ class. I'm using g++ on my linux box. Weird thing is, when I use the following block to check an integer value:
It works like a BOSS. It catches every possible invalid input possibility, even when I do nothing but type garbage on the terminal for ten minutes. HOWEVER, the same cannot be said for when I do the same for a double type variable:
For one reason or another, it either A) sets the value of the double to 0, which is a problem because it will end the program (assignment submission requirement, no getting around it) or B) it will go through an infinite loop. I've tried setting the value of base_number to something else immediately after the cin.ignore, it will go through a loop. I've tried to make use of flags (i.e. declaring a bool bad_input outside the loop, setting it to false after the cin.ignore statement, and altering the loop condition appropriately) and it STILL goes through an infinite loop. Seriously! Compile each of these blocks in g++ and you'll see what I mean. It's crazy. Anyway, I'm running out of ideas, time, and patience. Any help at this point would be massively appreciated. Thanks in advance! | |||||
|
|
|||||
| jlb (170) | |
The ignore() call should still be using numeric_limits<streamsize>::max not double, or int. Remember you are clearing the input buffer, which is a series of characters. Also you probably should be using numeric_limits<streamsize>max instead of the int in both of your snippets. A streamsize may hold larger numbers than an int and ignore is prototyped as:istream& ignore ( streamsize n = 1, int delim = EOF );Jim | |
|
|
|
| sirjames2004 (3) | |
|
Thanks for the reply Jim! Unfortunately when I swap out double/int for 'streamsize' it says "error: ‘streamsize’ was not declared in this scope" when I compile it again in g++. Is there another library I need to include? I got the following currently in my program: #include <iostream> #include <iomanip> #include <limits> #include <cmath> | |
|
|
|
| iHutch105 (1092) | |
std::streamsize
| |
|
|
|
| jlb (170) | |
|
Did you properly scope std::streamsize? | |
|
|
|
| sirjames2004 (3) | |
|
Fixed it. My cin,ignore statement for both snippets is now as follows: std::cin.ignore((std::numeric_limits<std::streamsize>::max)(), '\n'); This seems to have fixed the issue. Both blocks catch any invalid input now. Thanks a lot! :-) | |
|
|
|