How am i able to display an error message and exit the program when a character is accidentally entered by a user when the scanf statement expects an integer ( or double ), instead of having the prog crash.
How am i able to display an error message and exit the program when a character is accidentally entered by a user when the scanf statement expects an integer ( or double ), instead of having the prog crash.
This was on the FAQ I hope this helps
Code:#include <stdio.h> #include <stdlib.h> int main(void) { char buf[BUFSIZ]; char *p; long int i; printf ("Enter a number: "); if (fgets(buf, sizeof(buf), stdin) != NULL) { i = strtol(buf, &p, 10); if (buf[0] != '\n' && (*p == '\n' || *p == '\0')) printf ("Valid number of %d entered\n", i); else printf ("Invalid number entered\n"); } return(0); }
Last edited by linuxdude; 05-22-2004 at 07:01 PM.
If you are using scanf, look at this
Code:int x, retval; retval = scanf("%d", &x); if(retval == 0) { printf("They entered a not interger.\n"); } else { /* you are fine */ ...
Help populate a c/c++ help irc channel
server: irc://irc.efnet.net
channel: #c
both of these solutions work on their own, so thats cool, but now ive got a different problem.
The code checking for an integer or invalid character is within a case statement... like so:
switch ( choice )
{
case 1:
printf( "\n\n\tPlease enter the number to be evaluated (in radians): " );
if (fgets(buf, sizeof(buf), stdin) != NULL)
{
i = strtol(buf, &p, 10);
if (buf[0] != '\n' && (*p == '\n' || *p == '\0'))
printf ("Valid number of %d entered\n", i);
else
printf ("Invalid number entered\n");
}
same as above for case 2: case 3: ....
with either solution inside the case statement, it skips the fgets statement and the next few user entries, after printing "invalid number entered" .
I am looking for a way to recognize the invalid character and immediately exit the switch statement and either exit the prog. or return to another function call without any extranneaous input.
First up, if you have code that is repeated throughout, it sounds like you should make that bit into a separate function of its own.
Anyway, back to your problem, are you using scanf() somewhere else in the program? If you're having troubles with "it skips the fgets statement", that normally means you've got some data in the input buffer already, before you call fgets(), and this is normally a symptom of mixing it with scanf().
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]