|
-
Dec 19th, 2001, 11:51 AM
#1
Validate input numbers in C++
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!!
-
Dec 19th, 2001, 03:25 PM
#2
Addicted Member
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!
-
Dec 19th, 2001, 04:17 PM
#3
Thanks!!!
Thanks I help myself much!!!!!
-
Dec 20th, 2001, 06:29 AM
#4
Addicted Member
-
Dec 20th, 2001, 10:24 AM
#5
Fanatic Member
Or you could try something like:
PHP Code:
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.
Alcohol & calculus don't mix.
Never drink & derive.
-
Dec 20th, 2001, 10:44 AM
#6
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 )
Code:
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
}
-
Dec 20th, 2001, 11:36 AM
#7
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 )
Code:
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
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|