Search code examples
ccharbufferscanfgetchar

scanf/getchar working correctly only first time through loop?


I'm trying to have the user enter in a number as many times as they want (and create a linked list node for each of the numbers).

However, I've tried multiple method of clearing the character input buffer but to no avail. Strangely, the code will execute once through but not execute correctly the second.

For example, with the code below, the terminal reads:

would you like to enter an integer?
y
Enter an integer: 4
would you like to enter an integer?
y
**program terminates**

And before when I was using scanf("%c", yesno); I would not even be able to input 'y' on the last line. It just terminated.

struct node *read_numbers(void){
    struct node *first = NULL;
    int n; char yesno;
    yesno = 'y';
    while( yesno == 'y'){
        printf("Would you like enter an integer ((y) for yes/(n) for no):\n");
        yesno = getchar();  
        while(getchar() != '\n');
        if(yesno == 'y'){
            printf("Enter an Integer:");
            scanf(" %d", &n);
            first = add_to_list(first, n);
            } else {
                return first;
                }
        } // end while
    }

I read up on character inputs and buffers, and supposedly the getchar() method should work. Am I utilizing it wrong? I've also tried scanf() with extra spaces before and after the "%c", but to no avail.


Solution

  • You need to digest the newline after the scanf. You can do what you're doing above in the code:

    scanf(" %d", &n);
    while(getchar() != '\n');
    first = add_to_list(first, n);