Can I Read In A Character Without The Return Key 'n'? (C)

- 1 answer

Im trying to verify if the user enters the right value with the return values. He should enter an even number between 0 and 100.

I think I got it right, but now my problem is, that the user has to enter the "enter" key twice to end the scanf function.

Do I have another possibility to avoid the user from doing so?

Heres the code I wrote:

#include <stdio.h>
#include <windows.h> 

int main( void )
   int ok, input = -1;
   char c;

   while(input < 1 || input > 100 || input%2 != 0) {      //repeat loop if Input is not even or betwenn 0 and 100
       printf("Enter an odd number between 1 und 100: ");
       int ok = scanf("%d%c", &input, &c);                //Input is correct if ok = 2 and c = 10'\n'

       while((c = getchar()) != '\n' && c != EOF) {}      //this loop empties the input buffer to avoid infinite loops if users enters a character         

   printf("You habe chosen the number %d ", input);

   return 0;


I believe you don't need the second while loop at all.

As suggested above, the scanf() is waiting for enter to be pressed once, and then getchar() is waiting after.

If you remove the second while loop, the code should run correctly and only require the enter key to be pressed once.

I hope this helps!