how do you make it so that if the user inputs anything but integers the program will give an error and prompt the user to enter again?
ex. 123456## or ?? should give an error and prompt the user to enter again
help?
how do you make it so that if the user inputs anything but integers the program will give an error and prompt the user to enter again?
ex. 123456## or ?? should give an error and prompt the user to enter again
help?
You use an input function to get the data, then you parse the data yourself, or use built-in functions to parse the data, and check their output, and you put all of that in a loop.
Mainframe assembler programmer by trade. C coder when I can.
One way would be to take your input as a char string and check each character against it's ascii value:
This doesn't accept decimals or + or - in "the number" but you should be able to modify it to do so.Code:#include <string.h> #include <stdio.h> int main() { int i; char input[1024]; scanf("%s",input); for (i=0;i<strlen(input);i++) { if (input[i]<48 || input[i]>57) { puts("Not a number!"); return -1; } } printf("Number was %d\n",atoi(input)); return 0; }
Also you could look at the documentation for atoi and strtol for another strategy.
Last edited by MK27; 11-26-2008 at 05:19 PM.
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
i appreciate the replies!
is there anyway i can use it with an int instead of a char?
the digit has to be a 6 digit number, so this is what i have so far
Of course, this is so only integers that are 6 digits are allowed.. but im having trouble with anything besides integers. How would I implement what you have above into this? O.OCode:while(int < 100000 || int > 999999) { printf("Invalid! Enter again: "); scanf("%d", &int); }
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.