PDA

View Full Version : how to reduce "cin" error checker c++



Dj Still
April 2, 2009, 06:56 PM
hey i want to reduce error when am inputting values.

for example

my program prompt for a username which should be a string value
if the user enter an integer i want to send on error message and ask the to retry and enter an string or char value.

the same if i prompt the user for a int... if the user a string my programm will crash how to prevent this.


thank you

Mixmasterxp
April 8, 2009, 04:04 PM
regex is worth learning not only for this application. look up regular expressions.

crosswire
April 8, 2009, 05:45 PM
There is a lot of string functions in headers that can become useful as well
It all depends on the level of coding you want to achive.

If you can use the stdlib header, not sure of the name. No c++ compiler at the moment and too lazy to google. Then you might have some functions that can be used to search for chars in strings

The basic idea is to take the input as a string type all the time.

For user name, collect the string in a loop
eg

while(true)
{
//collect user
string user
IsStringAPureNumber();
if false
break;
}

then


bool IsStringAPureNumber()
{
//check if each char is a number
}


You can know if any input was a number string or a alphabet string


... if the user a string my programm will crash how to prevent this When you are cin into an int variable and an alphabet char was inputted, it tends to crash, so cin into a string variable even for the number.
To get the int from a number string use gcvrt() or related conversion functions. Basically string to int/double. I do not remember the function spelling or other conversion functioins in that header.

Somethings you can build a username validating function from basic string functions eg strcat()
Sometimes you find it easier to code it specifically from scarp
Sometimes if it is a homework, you are expected to do it one particular way.

Dj Still
April 10, 2009, 04:39 PM
hey could has help solve a problems that has baddering me a long time.
but am still having problems when the user enter an string value where an int was suppose to be input.

using dev c++

windows

Skele Drew
April 10, 2009, 04:50 PM
There should be library functions to check if a user's input is alphanumeric, digit, etc and to convert among the various types. Take ALL user input as strings and use these functions to check and convert based on its content.

*I actually made a lib of the ones I needed when i couldn't find them one time though :eusa_shif. Still buggy...*