# ! the headache code

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 :

[[email protected] logs]$ ./a.out 
Enter string1:string
Enter charEnter String2:who

 Read strings: string 
T
The expected output is:
[[email protected] 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. </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.

example:

#include < stdio.h>
#include < readline/readline.h >

main()
{
        char *str = readline ("Enter a line of text :");
        printf(str);
}

while compiling do,

$ gcc prg.c -lreadline 

It works fine.