Validating numeric values in c

You can use casting to check to see if an input number is an integer by comparing the input to the (int) cast of the number.Something like this should work: Here's something to add to your education: Learn to think like a programmer.I am doing a lab for an intro programming class I have to make sure that an integer is entered.I thought this would do it but when I put in a letter it repeats in an endless loop.In that case, you need to dispose of the input that caused the problem in the first place; if loop then reads the offending input character-by-character.Note that this function chooses to discard all the remaining input on the line.I found this solution in another post My prof posted this Im not sure how it helps but I thought it might help someone To make sure that a user-input number is an integer you can use the notion of casting.

You can, however, choose to make the program a little more user friendly and give the user the opportunity to try to enter the correct type of value.

These extra hidden characters are what is messing with your input and spawning the infinite while loop.

Luckily, I was able to parse through the extra characters one-by-one and get something working.

Other possible choices are to discard just the next character or word. The outer loop keeps going until the user successfully enters an integer, causing .

The reason behind this is when you hit return\enter on your keyboard, a newline character is passed in as input.

Leave a Reply