8

i am having trouble with this c language code:

 char st[2];

 printf("enter first value:");
 scanf("%c", &st[0]);

 printf("enter second value:");
 scanf("%c", &st[1]);

So my computer didn't ask me to enter the second value, I mean to say that it only print the first printf statement then I enter a character and then it only prints the second printf statement and program end without taking the second input.

Please help. What's wrong with this code?

-Thanks in advance.

Brad Mace
  • 27,194
  • 17
  • 102
  • 148
Peeyush
  • 4,728
  • 16
  • 64
  • 92
  • 1
    possible duplicate: http://stackoverflow.com/questions/1669821/scanf-skips-every-other-while-loop-in-c – Alam Oct 26 '10 at 12:32
  • It must be the day for `scanf` questions. [Same problem as this](http://stackoverflow.com/questions/4016073/scanf-fails-why), I think. []() – The Archetypal Paul Oct 26 '10 at 12:33

5 Answers5

10

Well it did. The character(s) produced by the ENTER key is present in the buffer already.

leppie
  • 115,091
  • 17
  • 196
  • 297
8

use fflush(stdin); function before the second scanf();. It will flush the ENTER key generated after first scanf();. Actually, your second scanf() is taking the ENTER as its input and since scanf terminates after getting an ENTER, it is not taking anything else by your side.

Dimanshu Parihar
  • 347
  • 2
  • 12
4

I think your problem is the second scanf is receiving the "Enter" key press.

nathan
  • 5,513
  • 4
  • 35
  • 47
4

You're getting the implicit newline you entered as the second character, i.e. st[1] is getting the value '\n'. An easy way to fix this is to include the newline in the expected format string: scanf("%c\n", &st[0]);

Derrick Turk
  • 4,246
  • 1
  • 27
  • 27
3

Change

scanf("%c", &st[0]);

to this

scanf(" %c", &st[0]);

That's a shotty answer (no error checking or anything) but its quick and easy.

Marm0t
  • 921
  • 9
  • 18