I've encountered a problem when validating a single-char scanf input in C and I cannot find an existing solution that works...
The scenario is: a method is taking a single letter 'char' type input and then validating this input, if the criteria is not met, then pops an error message and re-enter, otherwise return this character value.
my code is:
char GetStuff(void)
{
char c;
scanf("%c", &c);
while(c != 'A' || c != 'P')
{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &dtChar);
}
return c;
}
however, i got the infinite loop of error message no matter what input I type in. I read some other posts and guess it's the problem that %c specifier does no automatically get rid of the newline when I hit enter, and so far I have tried:
putting a white space before/after %c like:
scanf(" %c", &c);write a separate method or include in this
GetStuffmethod to clean the newline like:void cleanBuffer(){ int n; while((n = getchar()) != EOF && n != '\n' ); }
Can anyone help me with this problem please? Thank you in advance.
c != 'A' || c != 'P'is always true. - n. 1.8e9-where's-my-share m.scanf(); it might be telling you EOF. You might well want to add a space before the%cin the conversion specifier, so as to skip white space (such as newlines) — usingif (scanf(" %c", &c) != 1) { …process error… }might be better. You say that including fixed code in your bigger program still left you in an infinite loop. You should think about how you will debug it — adding print statements or using a debugger. See How to debug small programs. - Jonathan Lefflerscanffor a single-character? Isn't that whatgetchar()(orfgetc) is for? You should also save and check the return ofscanf, e.g.int rtn = scanf ("%c", &c);so you can checkif (rtn == EOF) { /* handle user canceled input */ }- David C. Rankin