Scanf will not request input a second time

#include "stdio.h" int main(void) { int order, nextp, N=3; char cont; nextp = 0; printf("\nShould we continue (y or n): "); scanf("%c", &cont); if (cont != 'y') return; for(; nextp < N; nextp++) { printf("Enter order number: "); scanf("%d", &order); printf("you have entered %d\n", order); printf("okay now continue with cont\n"); printf("enter cont y or n: "); scanf("%c", &cont); if (cont != 'y') { printf("\nnot equal to y\n"); break; } printf("after intepreting t[0]"); } return 0; } 

The result is as follows

 Should we continue (y or n): y Enter order number: 45 you have entered 45 okay now continue with cont enter cont y or n: not equal to y 

The second entry was skipped. Why?

+6
source share
5 answers

due to the newline already in stdin, this happens. use

 scanf(" %c", &cont); 

instead

 scanf("%c", &cont); 

mark one space before% c.

+8
source

This is why scanf is not commonly used for character input. After the previous entry, the carriage returns to the left.

For example, if you have to add getchar() after entering the order, your problem will be solved, but this is not clean code. You can also see this explicitly by dividing cont != 'y' by cont != '\n' .

Instead, use getchar() for all of your inputs and check for \ n

+3
source

After scanf("%d", &order); consumes a number (in this case 45), after that there is one more line. You can use scanf("%d\n", &order) to consume the return.

Another answer to this question can be found here:

does scanf () leave a new char line in the buffer?

+3
source

For most conversions, scanf skips spaces, but for char format ("% c"), you must skip space using explicit format space ("% c"), as described here:

C - attempt to read one char

This is also explained in the scanf documentation, but it is confusing and it might be better to use something else, as others have mentioned.

+1
source

You can use fflush ()

 printf("enter cont y or n: "); fflush(stdin); scanf("%c", &cont); 
+1
source

All Articles