| hellfire1 (26) | |||
|
Hey all, Having trouble verifying an input is an integer. It's like this: I need to enter a number, and then check whether it's between 5 and 26, if so, it's acceptable, if not, it runs again to re-input the number after returning an error message. I have the verification of the numbers down, it's super easy, but I can't get it to re-run the loop when I enter something like: a, or a /. Instead, it acts like an infinite loop is occuring, which is doesn't make sense, so I'm guessing it has something to do with the int data type and causing overflow issues? Code segment is here:
Again, what I have should be working, logic wise. It checks if the number is less than 5, greater than 26, an alphabet character, or neither an alphabet character or numeric. If any of those are true, it should run the loop again, but instead I'm getting this crazy infinite loop if the input is anything but a number. How do I fix this? Thanks, -Drew | |||
|
Last edited on
|
|||
| shacktar (1143) | ||||
See one of my recent posts on the use of cin.fail()http://www.cplusplus.com/forum/beginner/91623/ I would recommend writing a separate function, i.e. int GetNumericInput();that's in charge of getting numeric input from the user (and continually asking them until they input something numeric). Then, your grid size check can be simplified to something like this:
| ||||
|
Last edited on
|
||||
| jim80y (181) | |
|
The reason you're getting an infinite loop is that if cin doesn't read a valid integer, grid_size will have the value 0xCCCCCCCC, which is way less that 5 and causes your second loop condition to evaluate true - the loop runs again. Hope that helps! Edit: I just re-read what you'd written - where's the infinite loop you're talking about? Jim | |
|
Last edited on
|
|
| hellfire1 (26) | |
|
Jim, as I had mentioned, there's no actual infinite loop present, it should always at least stop and ask for another input. However, if you take that code, and enter an "a" or a symbol like a "/" when prompted for a number, it will continually output the error message as if it were an infinite loop, and never prompt for new input. It's very frustrating. To shacktar^ I'll be sure to check that out! Hopefully it can clear up my issue! | |
|
|
|
| iHutch105 (1091) | |||
| |||
|
Last edited on
|
|||
| hellfire1 (26) | |
Well, while I'm not really sure what int argc, char* argv[] means or affects, I solved the input issue with a combination of both of your solutions. I simply added cin.clear(); and cin.ignore(); statements to my input feature, and cut the extraneous input step I had before and added it right into the loop.Then I broke things down into smaller, more portable functions like shacktar was doing. The code now works perfectly, and I'm having no issues. Thanks all!! -Drew | |
|
|
|