Marc
Marc

Reputation: 1184

Wait for user input in while(1) 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!

Upvotes: 4

Views: 8691

Answers (4)

hackitect
hackitect

Reputation: 141

invoer=getchar(); 

is a solution if you flush stdin before using it for the next iteration like so:

fflush(stdin);
invoer=getchar();

Upvotes: 0

Jay Bhalodi
Jay Bhalodi

Reputation: 387

simple and sweet solution invoer=getchar(); that will wait for a character as well as store in to the variable. no need to write scanf

Upvotes: 0

LearningC
LearningC

Reputation: 3162

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;

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409472

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.

Upvotes: 3

Related Questions