0

I tried to run the following program:

int main(){
    char a;
    char b;
    char c;

    printf("\nenter a: ");
    scanf("%c", &a);

    printf("\nenter b: ");
    scanf("%c", &b);

    printf("\nenter c: ");
    scanf("%c", &c);

    return 0;

}

upon running the program it prompts you to enter a value for a. once you do, you are prompted to enter a value for b, however you are not allowed to input a value because the program skips the scan and then prompts you again to input a value for c which is not skipped. I can initialize a and c, but not b. and I have no idea why. I read somewhere that using %[^\n] in the scanf, but I tried using it and I don't think I used it correctly because it still wasn't working.

this is the output (with some input examples):

enter a: 1

enter b: 
enter c: 1

process returned 0 (0x0)
Angel Garcia
  • 1,547
  • 1
  • 16
  • 37

3 Answers3

0

Instead of "%c", use " %c".

Without the space, scanf does not skip white spaces when the format specifier is %c. That is initially confusing since it will skip white spaces for other format specifiers, such as %d, %f, %s, etc.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

When you press enter, that adds a character to the input queue, which is then read into b.

You can either explicitly read a character to ignore it, or you can use (for one alternative) %1s to read a single-character string (which will skip white-space, including the new-line character entered when you press enter.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

'\n' becomes the input for variable b after you press enter. so to take care of this, use getchar() which will take care of '\n'.

int main(){
    char a;
    char b;
    char c;

    printf("\nenter a: ");
    scanf("%c", &a);
    getchar();    

    printf("\nenter b: ");
    scanf("%c", &b);
    getchar();

    printf("\nenter c: ");
    scanf("%c", &c);

    return 0;

}