code not taking 2nd character input

My code below is supposed to take 3 inputs, first 2 characters and 3rd floating. It just takes first input and ignores the 2nd. Here is the output I get.

1
2
3
4
5
6
7
Enter first character ? A
Enter second character ? Enter real value ? U
First character is: A
Second character is:

Real value is: 3.765E-039
Integer value is: 50


Here is the actual code. Please guide me where I am making a mistake.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
#include <conio.h>

int main (int)

{

char ch1,ch2;
float x;
int n;

printf ("Enter first character ? ");
scanf ("%c", &ch1);
printf ("Enter second character ? ");
scanf ("%c", &ch2);
printf ("Enter real value ? ");
scanf ("%f", &x);

n = 50;

printf("First character is: %c \n",ch1);
printf("Second character is: %c \n",ch2);
printf("Real value is: %.3E \n",x);
printf("Integer value is: %d \n",n);

getch();
return 0;

    }


** btw, I am using dev c++ compiler.
Last edited on
closed account (zb0S216C)
Insert a space before %c within the second scanf( ).

Just for the record, Dev-C++ isn't a compiler. Dev-C++ uses the MinGW compiler.

Wazzak
Thank you for clarifying and also for correcting my code. It worked after adding a space. May I ask why it would only be required for the 2nd character. First character input works without the space.
closed account (zb0S216C)
Allow me to elaborate. Before inserting the space, the entered characters were stored into the input buffer, which would've looked like this:

Input Buffer (before inserting a space): 'a', '\n'

When the input buffer is read, it's read as if it's a word, not two independent characters. However, after inserting the space, your input buffer would've looked like this:

Input Buffer (after inserting a space): 'a', '\n', ' ', 'b'

The space basically separated the two characters, which no longer resembles a word.

So, when scanf( ) saw the '\n' within your input buffer (after pressing enter), it used that escape sequence as the value for your second input (ch2), hence the skip.

Wazzak
Last edited on
You are inspiring for a wanna be coder. Thanks again Wazzak.
Topic archived. No new replies allowed.