Search code examples
cgetchar

What is happening with getchar?


I am just looking for an explanation here. I have a simple program loop:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    while(1)
    {
        printf("ready to begin? Enter y or n: ");
        char begin = getchar();
        if(begin == 'y')
        {
            break;
        }
        else if(begin == 'n')
        {
            printf("good-bye.");
            return 0;
        }
    }
    printf("hu-ray\n");
    return 0;
}

When I compile and run this, much of the behavior is expected. Example: 'y' as input.

Ready to begin? Enter y or n: y
hu-ray

'n' as input also gives expected behavior along with just hitting ENTER.

Ready to begin? Enter y or n: n
good-bye.
Ready to begin? Enter y or n: 
Ready to begin? Enter y or n:

However, if I enter anything else, 'k' for example, I get this:

Ready to begin? Enter y or n: k
Ready to begin? Enter y or n: Ready to begin? Enter y or n:

more bizarre, the output of entering '12345':

Ready to begin? Enter y or n: 12345
Ready to begin? Enter y or n: Ready to begin? Enter y or n: Ready to begin? Enter y or n: Ready to begin? Enter y or n: Ready to begin? Enter y or n: Ready to begin? Enter y or n

Even after looking over the man page for getchar() I just do not understand what is happening here. Does anyone have an explanation?


Solution

  • Every call to getchar() returns one character. So when you type a line at that prompt the next few characters are already provided to the next calls to getchar().

    You probably want to call fgets().