I'm trying to make a loop in C where the program calculates the avarage of 2 numbers and then waits for user input. If the user input is 'G' then the loop will break. However this is not working currently because it's (in a strange way) a infite loop.
My code is:
while(1){
pogingen++;
gem = (minimum+maximum)/2;
printf("%i",gem);
scanf("%c",&invoer);
if(invoer=='L'){
maximum = gem;
}
if(invoer=='H'){
minimum = gem;
}
if(invoer=='G'){
printf("%i",pogingen);
break;
}
}
I tested it with these values: minimum = 1, maximum = 10. The result will be an infite loop of 5's. It doesn't even wait for the user input (which it's supposed to do.)
Thanks in advance for looking at this!
It doesn't even wait for the user input (which it's supposed to do.)
.
The program is not waiting to get the input means there is some character left in input buffer. possibly \n
from previous input. So clear the input buffer before reading input.
you can put,
getchar();
scanf("%c",&invoer);
before scanf()
inside loop;
The reason it doesn't wait for user input in some instances, is because when scanf
reads a character, you press the Enter key at the end of the of input, and that key is also stored in the input buffer. So the next iteration it will read that enter key.
This is easily solved by telling scanf
to discard trailing whitespace (which the newline character is):
scanf("%c ",&invoer);
/* ^ */
/* | */
/* Notice extra space here */
You might also want to print some error message if the user doesn't give valid input. Also, consider using toupper
, because the chances are the user will not give you an upper-case letter.
It might also be better to to use e.g. if ... else if ... else ...
instead. Or possibly use a switch
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With