How to use while(true) loop to write a program like this:

How to use while(true) loop to write a program like this:


Welcome to My Number Guessing Game.
I have a number in mind and you have to guess it.
In your input below, enter the comparator
followed by your guess. E.g. "= 15?"

At present only the '=' comparator is supported.

Good luck!

1. Take a guess at the number (1-25) I have in mind: [ENTER]
1. Take a guess at the number (1-25) I have in mind: 1
Only the equals comparator (=) is supported in this release. Try again
2. Take a guess at the number (1-25) I have in mind: =1?
Nopes. Try again.
3. Take a guess at the number (1-25) I have in mind: <1?
Only the equals comparator (=) is supported in this release. Try again
4. Take a guess at the number (1-25) I have in mind: [ENTER]
4. Take a guess at the number (1-25) I have in mind: [ENTER]
4. Take a guess at the number (1-25) I have in mind: =2
Nopes. Try again.
5. Take a guess at the number (1-25) I have in mind: =3?
Nopes. Try again.
6. Take a guess at the number (1-25) I have in mind: = 4?
Nopes. Try again.
7. Take a guess at the number (1-25) I have in mind: = 5?
Nopes. Try again.
8. Take a guess at the number (1-25) I have in mind: =6?
Nopes. Try again.
… etc …
18. Take a guess at the number (1-25) I have in mind: =16
Yay! You have guessed it!
You used 18 guesses.
Bye now.
Program ended with exit code: 0


And here is my work... but I get stuck... Need helps!
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
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    cout <<"Welcome to My Number Guessing Game. \n";
    cout <<"I have a number in mind and you have to guess it. \n";
    cout <<"In your input below, enter the comparator \n";
    cout <<"followed by your guess. E.g. \"= 15?\" \n \n";
    
    cout <<"At present only the '=' comparator is supported.\n";
    cout <<"Good luck! \n";
    
    char comparator;
    int guess;
    
    cin >> comparator;
    cin >> guess;
    
    istringstream = cin;
    
    istringstream (string userInput) >>comparator >>guess;
    
    useInput = (comparator, guess);
Last edited on
It seems like you want to loop while the guess is wrong not an infinite loop. Would be pointless to have an if statement to break instead of checking that before looping.

You can do something like:

1
2
3
4
5
do
{
    //tell them which guess they are on
    //get user guess
} while(guess != answer);


Also, I don't believe useInput = (comparator, guess); is valid. Maybe try something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
switch(comparator)
{
    case '>': //compare if it is greater than
    break;

    case '<': //compare if it is less than
    break;

    case '=': //compare if it is ==
    break;

    default: //invalid operator do something
}
Topic archived. No new replies allowed.