[OCLUG-devel] C Error Handling
    Chris Berry 
    chris_berry-list-oclug-devel at jm-associates.com
       
    Wed Jun 15 18:20:47 PDT 2005
    
    
  
Ok, I'm learning a little basic error handling with input strings.  The 
object is to prompt the user for a positive integer, and make them do it 
  over again if any other input is entered.  Here is what I have right now:
#include <stdio.h>
#define MAXLINE 100
int main (void) {
	char line[MAXLINE];
	int error, n;
	do {
		printf ("Input a positive integer: ");
		fgets (line, MAXLINE, stdin);
		if (sscanf (line, "%[0-9]", &n) == 1) {
			error = 0;
		}
		else error = 1;
		if (error) printf ("\nERROR: Do it again.\n");
	}
	while (error);
	return 0;
}
This works correctly for the following inputs:
3
-3
e
e3
but not for:
3e
Which it sees as valid input.  I think the problem is that it quits as 
soon as it sees the invalid character, but I haven't quite been able to 
wrap my ahead around how to get it to keep looking without creating an 
infinite loop.  Tried a few different things and looked on google but I 
think I'm not looking at it right yet.  Can someone give me a hint?
-- 
Chris Berry
chris_berry at jm-associates.com
Information Advisory Manager
JM Associates
"There is nothing so useless as doing efficiently that which should not 
be done at all." --Peter Drucker
    
    
More information about the OCLUG-devel
mailing list