Does Scanf / getchar only work correctly in the first loop?

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; } } // end while } 

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.

+1
source share
3 answers

You need to digest a new line after scanf. You can do what you do above in code:

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

Can I recommend using fgets as a safer alternative to getchar and scanf ?

As you noticed, these functions can buffer a new line and pass it to the next function, which is read from standard input.

With fgets you can save input in a char array and avoid such problems. In addition, you can still easily check if the input consists of only a new line:

 char user_input[10] = ""; printf("Would you like enter an integer ((y) for yes/(n) for no):\n"); /* get input or quit if only newline is entered, we only check the first char */ while(fgets(user_input, 3, stdin)[0] != '\n') { /* check if the first char is 'y', quicker to do than using strcmp */ if(user_input[0] == 'y') { int input = 0; printf("Enter an Integer: "); fgets(user_input, 5, stdin); /* get input again */ input = atoi(user_input); /* convert to int */ printf("Your integer is %d\n", input); printf("Would you like to go again? y/n:\n"); } else { return printf("No input there.\n"); } } 
+2
source

getchar gets data from stdin, while(getchar() != '\n'); just like flushing the stdin buffer. so the following code may work correctly

+1
source

Source: https://habr.com/ru/post/1239160/


All Articles