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.
#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;
}
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.
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:
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.