tags:

views:

75

answers:

5

hello

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.

+4  A: 

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

leppie
+1 I need to learn to type faster :D
nathan
+2  A: 

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

nathan
+1 from me, you were only 12 seconds behind me :)
leppie
+2  A: 

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
A: 

It must be the day for scant questions. Same problem as this, I think

Paul
A: 

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