Monday, July 27, 2009

C++ question. about chars and ints?

Ok i have a program. and in it an int called age i have a loop so that the range of age can only be between 0 and 125 and if it not it loops again and ask for you to enter age again and that works fine. but how would a make it loop again if some one entered a char or string instead of a number cuz when i do it goes into an infinite loop.





am also using the isdight func saying that when age is a number not in the 0-125 range loop again. when i run the program thru the first time it stores the number i entered for age. then when it ask to enter age again i inter a letter and i got it to say its not a number and doesnt go into a infinte loop but when i dont run it thru once and enter the letter in for age the first time it goes into an infinte loop.





i hope you can understand that and help thanx

C++ question. about chars and ints?
When the user inputs anything -- it's a string.





Read the user input in as a string and validate that it is numerical.





If it is, convert it to an int, double, etc. and proceed. Otherwise, loop.





I hope this helps!
Reply:does c++ have a try catch option?
Reply:what you can do is use scanf("%d", %26amp;age)


and detect if scanf() returns 1 for valid number input.


if scanf() returns 0, none of the input is valid and is not consumed. To get new input, must use fflush(stdin) to remove the input.


Alternately, try this


int age;


cin %26gt;%26gt; age; // If a non number is entered, it flags it as bad input


if (!cin) %26lt;%26lt; !cin is same as cin.bad()


{


cin.ignore(256, '\n'); %26lt;%26lt; This line removes the bad input from the stream otherwise it will keep detecting the bad input.


cout %26lt;%26lt; "Bad input";


}

flower beds

No comments:

Post a Comment