1
#include <stdio.h>

int main()
{

    char C, B;
    int x;



    printf("What comes after G\n");
    scanf("%c", &C);

    printf("What comes after O\n");
    scanf("%c", &B);

    printf("What is your age?\n");
    scanf("%d", &x);

    printf("You said %c comes after G, %c after T and you're %d years old? Right?", C, B, x);

    return 0;
}

The problem is whenever you run the code it skips the second question "What comes after O" and then asks "What is your age?"

The only way I could avoid the program skip the 2nd question was by adding a space to the code

printf("What comes after O\n");
    scanf(" %c", &B);

You can see the space between " and %c

Can you please explain this to me?

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
user3020714
  • 11
  • 1
  • 1
  • 2
  • 1
    Had the same problem> see here http://stackoverflow.com/questions/12653884/getchar-does-not-stop-when-using-scanf – oz123 Nov 22 '13 at 07:35

4 Answers4

3

You need to eat up the white space (i.e. new line) - as per the manual page http://linux.die.net/man/3/scanf

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
1

You can use scanf to eat the single character without assigning it to anything like this::

scanf( "%[^\n]%*c", &C ) ;

%[^\n] tells the scanf to read every character that is not '\n'. That leaves the '\n' character in the input buffer, then the * (assignment suppression) will consume the a single character ('\n') but would not assign it to anything.

Abhineet
  • 5,320
  • 1
  • 25
  • 43
1

The reason for this problem is newline character \n leftover by the previous scanf after pressing Enter. This \n is left for the next call of scanf.
To avoid this problem you need to place a space before %c specifier in your scanf.

scanf(" %c", &C);  
...
scanf(" %c", &B);
...
scanf(" %c", &X);  

A space before %c is able to eat up any number of newline characters.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

The problem is you are using scanf to get the character ..and a new line will be added at the end of each input from user . So the second time only the new line will be stored in the 'B' Because of the first input given by you ..

Instead of scanf , change it to getchar - your problem should get solved

Srikanth
  • 447
  • 2
  • 8