{
int num;
char ch;
clrscr();
printf(“Enter a number\n”);
scanf(“%d”,&num);
printf(“Enter a character\n”);
scanf(“%c”,&ch);
printf(“The value of num is %d and ch is %c”,num,ch);
getch();
}
The output of the program is shown below
12
Enter a character
The value of num is 12 and ch is
Wonder why this happens? Well let us look at the problem. When you type the number 12 and press ‘Enter’ key, the value corresponding to key press ‘1’ and ‘2’ is read from the input buffer and gets assigned to the variable ‘num’ once you press the ‘Enter’ key(delimiter). Now the value of the ‘Enter’ key is stored in the input buffer. So when you want to read a character, the value of the ‘Enter’ key which is stored in the input buffer is assigned to the character variable ‘ch’. This results in giving a wrong output. This is where the ‘fflush’ command comes into picture. The ‘fflush’ clears the specified buffer, so after getting the integer value we need to clear the input buffer (which stores the ‘Enter’ key value) before getting the character value. So the C program is changed as shown below.
printf(“Enter a number\n”);
scanf(“%d”,&num);
fflush(stdin);
printf(“Enter a character\n”);
scanf(“%c”,&ch);
Hope you know understood the importance of ‘ffush’ statement
5 comments:
thanks a lot
when we press the once enter key then 12 is stored in num variable , and the value of enter key stored in input buffer , but i could not understand that how ch variable gets a blank space
Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man, Keep it up.mobile phone repair in Novi
iphone repair in Novi
cell phone repair in Novi
phone repair in Novi
tablet repair in Novi
ipad repair in Novi
mobile phone repair Novi
iphone repair Novi
cell phone repair Novi
phone repair Novi
I Know a very wonderful car in usa . this car price is very nice. so you can buy it .
read more..
https://www.toyota.com/4runner/
Post a Comment