Following is a program that was given to my juniors in the C-Debugging finals. It was quite surprising that no one solved it, in an efficient manner!
Only Vivek and Sathish from third year did some justice to the program!
Only Vivek and Sathish from third year did some justice to the program!
#include<stdio.h>
void main()
{
int x;
char c,h;
clrscr();
printf("\n Enter a character:");
scanf("%c", &c);
printf(" The first character entered was:%c",c);
printf("\n Enter another character:");
scanf("%c",&h);
printf("\n The second character entered was:%c",h);
getch();
}
Solution:
#include<stdio.h>
void main()
{
int x;
char c,h;
clrscr();
printf("\n Enter a character:");
scanf("%c", &c);
fflush(stdin);
printf(" The first character entered was:%c",c);
printf("\n Enter another character:");
scanf("%c",&h);
printf("\n The second character entered was:%c",h);
getch();
}
Explanation:
stdin, gets the character and the enter as another character and it is set to h.
So h is not input at all!
fflush is an interesting function which flushes the unwanted content from the stream!
In java too we face this problem, I will get back to that in my tutorial!
No comments:
Post a Comment
Thanks for commenting in my blog...