Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for user input in while(1) loop

Tags:

c

while-loop

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!

like image 612
Marc Avatar asked Mar 20 '23 01:03

Marc


2 Answers

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;

like image 190
LearningC Avatar answered Mar 27 '23 22:03

LearningC


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.

like image 30
Some programmer dude Avatar answered Mar 27 '23 22:03

Some programmer dude