[OCLUG-devel] C Error Handling

Christopher Smith x at xman.org
Wed Jun 15 19:07:39 PDT 2005


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