I am trying to enter the user as many times as they want (and create a linked list of nodes for each of the numbers).
However, I tried several methods to clear the character input buffer, but to no avail. Oddly enough, the code will execute once, 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 used scanf("%c", yesno); , I could not even enter "y" in the last line. He just stopped.
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; } }
I read about character inputs and buffers, and supposedly the getchar () method should work. Am I using this incorrectly? I also tried scanf () with extra spaces before and after "% c", but to no avail.
source share