Search code examples
cgetchar

unexpected output with getchar()


char c = ' ';
while(c != 'x')
{       
    c = getchar();
    printf("threadFuncParam = %u\n", threadFuncParam);
}

In the above code snippet the print is printing threadFuncParam value twice every time I enter a character where as I expect it to print only once. As per my understanding very first time it enters while as condition is true and and then wait for user input at getchar call on entering a character it shall print the value and then if input character is not x it shall wait for another input at getchar call, but whenever i enter a character i see 2 prints ion screen for each input. I am not able to understand why?

What i'm trying to do here is that in main thread i am taking single char input from user and in worker thread i am incrementing a counter which gets incremented every second, i print the value everytime user input a char input until user enters 'x' character.


Solution

  • The simple issue here is that the console (input) sends the text to the stdin only when it encounters a enter key or ctr+d.

    As a result an extra \n goes into your input stream. This causes your program to read that character in the next iteration.

    A simple solution would be to read all white space characters in the stream.

    This can be done in multiple ways -

    If you need to discard any whitespace characters (including space, tabs, vtabs, newline), you can add

    scanf(" ");
    

    before the getchar();

    If you need to discard only the newlines which come as a result of pressing enter, you can add

    scanf("%*[\n]")
    

    before the getchar();

    This will eat up all the \n that come before the next character. But will not eat spaces.

    Finally if you want to discard only 1 \n

    You can do

    scanf("%*1[\n]");
    

    Remember though, in all the cases the scanf should be immediately before the getchar() because scanf would wait till it finds the next non white space character.

    All cases figured out with the help of comments from @chux.