|
-
Feb 5th, 2003, 06:50 PM
#1
Thread Starter
Addicted Member
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
-
Feb 5th, 2003, 07:14 PM
#2
Frenzied Member
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 =='.'));}
MSVS 6, .NET & .NET 2003 Pro
I HATE MSDN with .NET & .NET 2003!!!
Check out my sites:
http://www.filthyhands.com
http://www.techno-coding.com

-
Feb 5th, 2003, 07:32 PM
#3
Thread Starter
Addicted Member
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
-
Feb 5th, 2003, 08:52 PM
#4
Frenzied Member
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);
-
Feb 8th, 2003, 06:43 PM
#5
not
gets(answer);
but
fgets(stdin, answer, 9);
or you risk buffer overflows.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
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
|