It has been a long time, since the mid of the last year I were writing lots of code fragments in C programming language.
Ever since I started using Input console functions like scanf(), getchar() etc. I faced a common problem most of the times. But I ignored it by several adjustments. Last day I had a good mood for investigating and fixing this problem. Let me describe you the head scratching code.
main()
{
char a[10],b,c[10];
printf("Enter string1:");
scanf("%s",a);
printf("Enter char");
b=getchar();
printf("Enter String2:");
scanf("%s",c);
printf("n Read strings: %s %c %s",a,b,c);
}
Output :
[slynux@localhost logs]$ ./a.out
Enter string1:string
Enter charEnter String2:who
Read strings: string
T
The expected output is:
[slynux@localhost logs]$ ./a.out
Enter string1:string
Enter char:c
Enter String2:who
Read strings: string c who
But it doesn’t happen.
I was having some conversation with vu2swx (Sunil Sir). [ He is one of my Gurus to GNU/Linux]. He told me that this problem happens because, getchar() takes one character from standard input buffer (stdin). From googling a bit I learned that lots of people face the same problem and I couldn’t find some clearcut solution to the problem.
In order to prevent getchar to read a character from input buffer, adding an extra getchar before original getchar will help. The extra getchar reads off the unrequired character and hence expected output is produced. Sometimes clearing buffer may also help. fflush(stdin) can be used.
Modify the code as below:
main()
{
char a[10],b,c[10];
printf("Enter string1:");
scanf("%s",a);
getchar(); // to absorb the char from stdin buffer.
printf("Enter char:");
b=getchar();
printf("Enter String2:");
scanf("%s",c);
printf("n Read strings: %s %c %s",a,b,c);
}
During Computer LABs, I used to find lots of guyz struggling with this getchar() related this type of problem. I think this blog post may help my peers.