I am getting a weird problem while using scanf()
to store data into a union.
Here's my code
#include <stdio.h>
union Student
{
float score;
char grade;
};
int main(void)
{
union Student jack;
printf("Enter student score : ");
scanf("%f", &jack.score);
printf("Score : %f", jack.score);
jack.score=0;
printf("Enter student grade : ");
scanf("%c", &jack.grade);
printf("Grade : %c", jack.grade);
}
I get the following output
searock@searock-desktop:~/Desktop$ ./union
Enter student score : 12
Score : 12.000000Enter student grade : Grade :
but if I change my code to:
#include <stdio.h>
union Student
{
float score;
char grade;
};
int main(void)
{
union Student jack;
printf("Enter student grade : ");
scanf("%c", &jack.grade);
printf("Grade : %c\n", jack.grade);
printf("Enter student score : ");
scanf("%f", &jack.score);
printf("Score : %f\n", jack.score);
}
It gives me the exact output [correct output]. I know this is not a good example, but can someone explain me what's going wrong?
Modified Code : Add \n before format string. [scanf("\n%c", &ch);]
#include <stdio.h>
union Student
{
float score;
char grade;
};
int main(void)
{
union Student jack;
printf("Enter student score : ");
scanf("%f", &jack.score);
printf("Score : %f", jack.score);
jack.score=0;
printf("Enter student grade : ");
scanf("\n%c", &jack.grade);
printf("Grade : %c", jack.grade);
}