Search code examples
cscanf

C: scanf input single character and validation


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:

  1. putting a white space before/after %c like:

    scanf(" %c", &c);
    
  2. write a separate method or include in this GetStuff method 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.


Solution

  • #include <stdio.h>
    
    char GetStuff(void) {
        char c;
        scanf("%c", &c);
        getchar();
        while ((c != 'A') && (c != 'a') && (c != 'P') && (c != 'p')) {
            printf("invalid input, enter again (A for AM or P for PM): ");
            scanf ("%c", &c);
            getchar();
        }
        return c;
    }
    
    int main(void) {
        printf("Calling GetStuff()...\n");
        char x = GetStuff();
        printf("User entered %c\n", x);
        return 0;
    }
    

    You are using while (c != 'A' || c != 'P') as your loop conditional, but this will always return true. What you meant to use is the && "and" operator, instead of the || "or" operator.

    Also, call getchar() after your scanf statements, to capture the newline. This should work the way you want it to.