-
c integer checking
hi
i have a program where the user inputs an int. i wanna check if the int is valid, ie, no other characters besides numbers. i'm trying to get one character at a time from the int and check if 'isdigit()', but i'm not sure how to do this right or if there are alternatives...
any help is appreciated.
thank you
--770
-
Here is some code that I made. I know there is a function some where, maybe the STL that will do this as well, but I always use mine.
PHP Code:
#define _ISDIGIT 0x10
inline bool IsDigit(char *buf){return((*buf & _ISDIGIT) ? 1 : (*buf =='.'));}
-
i'm new to c, so is there anything simple i could use? i think isdigit is in ctype.h, but it only accepts one digit at a time. how do i get one digit at a time from a big integer.
also i don't understand your code, so i'm not sure how i can implemet it into mine..
thanx though
--770
-
You have to read string characters, then check if they are valid, then convert to int.
Code:
#include <ctype.h>
char answer[10];
char *buf;
int number=0;
memset(answer,0x00,sizeof(answer));
while(1){
printf("Enter a number: ");
gets(answer);
if(strlen(answer)){
/* this next line reads thru the string looking only for digits */
for(buf=answer;*buf && IsDigit(*buf);buf++);
if (!*buf) break; /* if we read to the end of the stringit was okay */
}
printf("\nInvalid response. Please use numbers only\n");
}
number=atoi(answer);
-
not
gets(answer);
but
fgets(stdin, answer, 9);
or you risk buffer overflows.