Saturday, May 22, 2010

Checking user input from c++ style strings?

I have to make a program where the user inputs an integer, and then I have to do some stuff to the integer, and then output it. Easy, but I want to make it so that the program checks if the user entered an integer or not; if they enter something other than an int, I don't want the program to crash.





I want to let the user enter something, and it will be stored in a c++ style string (from #include %26lt;string%26gt;), and then check the string to see if it is an integer. That way is safe, but I have no clue how to check a c++ style string.

Checking user input from c++ style strings?
The way I would design it is to have the input as a string, then set up a loop from 0 to strlen(input) - 1 and do an "isdigit" function on it. (if you're allowing negative numbers, then do special processing on the 0th byte of the string to account for this possibility).





Once isdigit is false, it's safe to leave the loop, throw the input away, and prompt for another try.





If the loop completes with isdigit always being true, then "atoi" it into a numberic varaible, then do your processing.
Reply:I think there might be an isInt function or something like that in the string library. I'd say go to cplusplus.com, search type checking, they'll have something good for you.


No comments:

Post a Comment