PDA

Click to See Complete Forum and Search --> : Validate input numbers in C++


omartalavera
Dec 19th, 2001, 10:51 AM
How validate input numbers in c++

Example:

int a;

printf("Number: ");
scanf("%i", &a);
if (a is number) {
}printf("a is number);
else{
printf("a is not a number);
}


in the sentence if ( ????? ) what to put ?

Thanks!!

[praetorian]
Dec 19th, 2001, 02:25 PM
I don't know if this helps you, but anyway, a header file, ctype.h/cctype.h includes several functions to determine if the input are numbers or not.....

take a look at msdn for more info.

To see if a is a number use
is...(a)

for example:

if(isdigit(a))
cout << a << " is a digit";


hope this helps!

omartalavera
Dec 19th, 2001, 03:17 PM
Thanks I help myself much!!!!!

[praetorian]
Dec 20th, 2001, 05:29 AM
ok....

Wynd
Dec 20th, 2001, 09:24 AM
Or you could try something like:char one = '1', nine = '9';

if ((a > (int)nine) || (a < (int)one))
printf("That is not a number\n");Those variables are there because I don't know the ASCII value of the characters. But, it should give you an idea.

jim mcnamara
Dec 20th, 2001, 09:44 AM
Most implementations of C, C++ have an is_numeric macro

Here is one just for numbers, no + - or . chars:

#define is_numeric(x) ((char)x >47 && (char)x < 58 )


int check_num(char *s){
int i;
char *buf;
buf=s;
for(;;){
if(!is_numeric(*buf) return 0; // handle null strings
if(*buf==0x0) return 1;
buf++;
}
// with well-formed string we should never get here
}

jim mcnamara
Dec 20th, 2001, 10:36 AM
Most implementations of C, C++ have an is_numeric macro

Here is one just for numbers, no + - or . chars:

#define is_numeric(x) ((char)x >47 && (char)x < 58 )


int check_num(char *s){
int i;
char *buf;
buf=s;
for(;;){
if(!is_numeric(*buf) return 0; // handle null strings
if(*buf==0x0) return 1;
buf++;
}
// with well-formed string we should never get here
}