[OCLUG-devel] C Error Handling

Chris Berry chris_berry-list-oclug-devel at jm-associates.com
Thu Jun 16 19:38:39 PDT 2005


Well, that didn't quite work, and to top it off it threw in a nice 
infinite loop, but it did inspire me somewhat and here's the working 
code I came up with:

#include <stdio.h>

#define MAXLINE 100

typedef enum valid_response { invalid = 0, valid } valid_response;

valid_response is_valid (char *);
void get_input (char *);

int main (void) {
	char line[MAXLINE] = {};

	get_input (line);
	while (is_valid(line) == invalid) {
		printf ("\nError: Do it again.\n");
		get_input (line);
	}

	return 0;
}

void get_input (char * line) {
	printf("Input a positive integer: ");
	fgets (line, MAXLINE, stdin);
}

valid_response is_valid (char * line) {
	int i;
	for (i = 0; i < MAXLINE; i++) {
		if (isspace (line[i])) break;
		if (isdigit (line[i])) continue;
		if (!isdigit(line[i])) return invalid;
	}
	return valid;
}

Thanks for the help!

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

Christopher Smith wrote:
> Chris Berry wrote:
> 
> 
>>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?
> 
> 
> Hmm.. some functional decomposition might help here. Make a function
> with this kind of a prototype:
> 
> enum valid_response { invalid = 0, valid};
> valid_response isValid(const char* aLine);
> 
> Also a function for actually getting the line (this is just tidyness):
> 
> void getInput(char* aLine) {
> printf("Input a positive integer: ");
> fgets(aLine, MAXLINE, stdin);
> }
> 
> Then your loop is just:
> 
> getInput(line);
> while (isValid(line) == invalid) {
> printf("\nError: Do it again.\n");
> getInput(line);
> }
> 
> The reason I suggest this functional decomposition is that it makes the
> program structure clearer, and it's easier to see where your problem is.
> Clearly, you aren't getting the response from isValid() that you want if
> aLine is "3e". So the question is, what is that criteria? Whatever it is
> should make 3e invalid, but you haven't defined it.
> 
> I'm going to guess that the criteria is "all aLine's characters are
> numbers". So then you just need to do that. Something like:
> 
> int isValid(const char* aLine) {
> const char* iter = aLine;
> while (*iter != '\0') {
> if (!isdigit(*iter)) {
> return invalid;
> }
> }
> 
> return valid;
> }
> 
> --Chris


More information about the OCLUG-devel mailing list