yes or no option in the loop

This is a simple guess the number program. I am trying to put an option that asks the user "Would you like to play again? (y or n). If the user press the y it should start the loop again but I can't find out the logic. Can I have some help please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main(){
  srand(static_cast<unsigned int>(time(0)));
  int number{1+rand()%1000};
  int guess{0};
  cout << "I have a number between 1 and 1000"
   << "\nCan you guess my number?"
   << "\nPlease type your first guess." << endl;
  char choice;
  while(true){
    cin >> guess;
    if(guess == number){
      cout << "Excellent you guessed the number!" << endl;
      cout << "Would you like to play again? (y or n)" << endl;
      cin >> choice;
      if(choice=='n' || choice == 'N'){
          return false;
      }
      else if(choice == 
      'y' || choice == 'Y'){
          return true;
      }
    }
  
  else if(guess < number){
      cout << "Too low. Try again." << endl;
  }
  else if(guess > number){
      cout << "Too high. Try again." << endl;
  }
  }
}
return in main ends the program. it that is a zero, it is normal execution, otherwise, it is an error code.
so your line 26 returns an error code (of 1, which is bool == true's int value).

just remove the whole 'y' block. if they enter a 'n', exit, if not, keep going.

I think you also may want to have it tell you what to do after the 'y', so you need a little editing to clean it up after you get the y loop working
Last edited on
Topic archived. No new replies allowed.