0

After than ı find the answer.I get 2 times the question that"Excellent!..like to play again(y or no);.Even if ı write y or n.Problem not change to depends the answer.(By the way ı am sorry for my bad english).

I have tried to change position of that statment(if(answer..) to the first line of the while or end line or smth like things.Also ı have tried put break somewhere(ı think the problem is not about to this but ı tried).

int main() {
    srand(time(NULL));
    int guess,number;
    char answer;
    number=1+(rand()%1000);
    printf("I have a number between 1 and 1000\n");
    printf("Could you guess my number?\n");
    printf("Please type your guess\n");
    while(1) {
        scanf("%d",&guess);
        if(guess==number) {
            printf("Excellent!You guessed the number!Would you like to play again(y or n)");
            scanf("%c",&answer);
            if(answer=='y') {
                number=1+(rand()%1000);
                printf("I have a number between 1 and 1000 \n");
                printf("Could you guess my number? \n");
                printf("Please type your guess \n");
            }
            else if(answer=='n') {
                return 1;
            }
        }
        else if(guess>number){
             printf("Too high.Try again.\n");
        }
        else if(guess<number){
            printf("Too low.Try again.\n");
        }
    }
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • Possible duplicate of [Why is scanf() causing infinite loop in this code?](https://stackoverflow.com/questions/1716013/why-is-scanf-causing-infinite-loop-in-this-code) – Govind Parmar Jan 31 '19 at 21:14
  • Thanks man.That was also correct. –  Jan 31 '19 at 21:32

1 Answers1

1

In your code, the following two statements taking input from console will be executed:

scanf("%d",&guess);
...
scanf("%c",&answer);

When scanf("%d",&guess); is executed, it will read a number from stdin, but it will leave the final new line (which you have to enter in a buffered stdin to finish input) in the buffer. The subsequent scanf("%c",&answer); will immediately read in this new line into answer,without giving the user the chance to enter any further letter.

Write...

scanf(" %c",&answer); 

such that any blank is consumed before reading in the "actual" character.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58