# how to determine if user input is an int

• 10-06-2001
sizzle_chest
how to determine if user input is an int
This is not part of my assignment, but I would like to figure out how to test the user input to be sure it is an integer. Is there a native function that I can use? If nit can some one point me in the right dirrection because I am drawing a blank. At first I thought I would do this by comparing the ascii values but I did not figure out how to implement it. Here is the assignment that is actually finished and working. It compares two arrays to figure out the taxrate of an income. Would like to test the variable aswer.

#include <iostream.h>
#include <stdlib.h>

int main()
{

const int max = 5;
int answer = 0, counta = 0, countb = 0, index = 0;
int income[max] = {0,10000,20000,50000,100000};
int tax[max] = {0,5,10,15,20};

for (counta = 0; counta < max; counta++) {
for (countb = 1; countb < (max + 1); countb++) {
index = counta; }

}
}

cout<<"Your taxrate is "<< tax[index] << "%" << endl;
endl << endl;

system("PAUSE");
return 0;
}

Thanx
• 10-06-2001
zen
This question should be on the C++ board.

You can either get the input as a character and then covert to an int, or test for cin.fail() which will set the fail state if a non-numeric character is passed when an int is expected.
• 10-06-2001
mlupo
you can use the isdigit() function to test whether or not a character in a character string is a digit.
if it is a digit, you an use atoi() to convert a character that represents a digit to an integer.

for example:

char somestring[80];

strcpy(somestring, "123");
strpy just copies "123" into the array.

then if you did
isdigit(somestring[0]; where 0 is the first position in the character array.

isdigit will return a non-zero integer (1-9) if it finds that the character you input is a digit. It returns 0 if it isn't. Now you can use that to make decisions with. bearing in mind that something that evaluates to 0 is the same as being "false" any non-zero would be equivilent to "true"

if( isdigit(somestring[0]) )
do something
else
do something else.

I hope this helps
• 10-06-2001
Unregistered
All console input is text, therefore, you know that they haven't input an integer. See how easy that was?

Quzah.
• 10-06-2001
zen
that