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.
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
Modify the code as below:
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. </stdin>
UPDATE 18.05.2k8 :</strong> Here is the right way to resolve this problem :)
Considering the comments on this post, I tried out gnu readline library. It solves the problem.
char * readline (const char *prompt);
readline function will return a pointer to a string line and we can pass the text to be prompted. it saves two line code into one line.
while compiling do,
It works fine.