Loops, if, else

Pages: 12
I am new to c++. I am trying to experiment to better understand how the fundamentals work. So I will cut to the chase.

I am trying to make a basic guessing number game. I did it properly accourding to an online tutorial. The problem comes in when I try to introduce a "play again" line. I do not yet know how to loop the program back to a certain point within the program so I am just copying the questions with if or else. It seems to work but it automatically enters something in and ends the program. Below is the code. If you could explain what I am doing wrong and what the program is doing I would appreciate it. If you could explain how to do a loop to the beginning if the user wants to play again, that would be greatly appreciated.

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
38
39
40
41
42
43
#include <iostream>

using namespace std;

int main()
{
    int num;
    int yes;
    int Yes;

    cout<<"Enter a number:  \n";
    cin>> num;
    cin.get();

        if (num==5){
            cout<<"Congradulations, you guessed right.\n";
            }
        else {
            cout<<"You guessed wrong.\n";
            }
    cin.ignore();

        cout<<"\nWould you like to play again? (Yes or No)\n";
        cin>> yes, Yes;
        cin.ignore();

            if (Yes==Yes, yes==yes){

                    cout<<"Enter a number:  \n";
                    cin>> num;
                    cin.ignore();

                if (num==5){
                    cout<<"Congradulations, you guessed right.\n";
                    }
                else {
                    cout<<"You guessed wrong.\n";
                    }
                }
            else
                cout<<"Thank you for playing.\n";
    cin.get();
}

Enter a number:
3
You guessed wrong.

Would you like to play again? (Yes or No)
yes
Enter number:
You guessed wrong.

Process returned 0 (0x0)   execution time  :  7.661 s
Press any key to continue
1) You don't have any loops here. Whatever you want to loop, stick in a loop.
2) Yes==Yes will always be true
3) cin>> yes, Yes doesn't do much.

Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main()
{
	char play_again = 'y';

	while (play_again == 'y' || play_again == 'Y') // Everything needs to go in a loop
	{
		cout<<"Enter a number:  \n";
		cin>> num;

		if (num==5)
			cout<<"Congradulations, you guessed right.\n";
		else
			cout<<"You guessed wrong.\n";

		cout<<"\nWould you like to play again? (y/n)\n";
		cin>> play_again;
	}
	
	cout<<"Thank you for playing.\n";
}
To make your code a lot shorter, here is a loop implemented into your program, it's called the do while loop:
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
#include <iostream>

using namespace std;

int main()
{
    int guess; // Variable to hold user's guess
    char playAgain; // Variable to hold user's choice

    do { // Ensures the loop is run atleast once
        cout<<"Enter a number:  \n";
        cin>> num;
        // Ignore up to 256 characters after num, or until a line return
        cin.ignore(256 '\n');

        if (num==5)
            cout<<"Congradulations, you guessed right.\n";
        else
            cout<<"You guessed wrong.\n";

        cout<<"\nWould you like to play again? (Y/N)\n";
        cin>> playAgain
        // Ignore up to 256 characters after num, or until a line return
        cin.ignore(256 '\n');
    // If the user entered a 'y' or 'Y' loop back to the do
    }while(playAgain == 'y' || playAgain == 'Y');

    // User typed something other than 'y' or 'Y'
    cout << "Thank youfor playing.\n";
    cin.get();
}


Notice how much simpler it is?

Edit: Something I did notice too was that your second attempt to play the game, you entered "yes" into a variable with type int. int's can only hold numbers -4,-70,546,32,0, not letters. Since you don't know strings yet, I opted to show you with a character.

The other issue was that since you were trying to put characters into your Yes and yes variables, they were overflowing into the cin buffer. That is what caused your program to end immediately after hitting enter after typing yes.
Last edited on
Wow, I'm a dope. Thanks so much. I was looking into loops. But, the intro to them deals with counting up to number and I wasn't understanding how you would apply that.

This a more simple approach than what I was doing. Though I ran into a bug which maybe you could help me understand how to fix it.

When asked to play again If you type 'yn' It speeds through:
Would you like to play again...
Enter a number.
You entered wrong.

When I debug it I have to ctrl+c to stop it.

If you enter 'ny' it doesn't do this. It just ends the program.
Last edited on
Read my edit. I added in the cin.ignore(256, '\n'); lines since I saw you were having that issue. You're storing the n into the buffer, and then it will ask you to play again. The ignore will allow the first character you typed to be stored into the variable playAgain, while everything after that will be discarded.
Thanks so much! This is awesome. Forgive me for getting over excited to a guessing game ha

How would I make the number a random number. If you guess the number and play again it is the same.

I also noticed if you enter y or n when you are suppose to enter a number it repeats over again. Have to force stop. If you enter any other letter it ends the program.
Last edited on
If you're trying to do error testing, you need to add another while statement in there, and I don't believe you have enough knowledge on C++ to be able to do that yet.

Same goes for the random numbers, but that one is easier to implement. Add these #includes at the top:
1
2
#include <cstdlib> // For srand() and rand()
#include <ctime> // For time() 


Add this code at the beginning of main:
srand(time(0));

Add this where you want a random number:
(rand() % n + x)

n should be the range of numbers, 0-n, would be 0-19 if you enter 20.
x should be the starting number, x, would be 1-20 is you did rand() % 20 + 1

Hope that makes a little more sense.
Thanks! You have been beyond helpful. I just need to test it to see if it is working. I'll see how long it takes me to guess correct.. ha

Thanks again!
I forgot to mention, srand() seeds the randomizer. It's hard to explain exactly how this works, but there is no such thing as a random number in a computer, but it can appear random to us. Without seeding the randomizer, you will always get the same exact numbers.

A seed is a value, and that value corresponds with a set list of meaningless numbers, to us anyways. You can select any seed that you want, but no matter what you pick, you'll always get the same set of numbers everytime. But if we seed it using the time(0) (meaning current time), the odds that we're ever going to run the program with exactly the same seed is about as close to impossible as you can get.

Since the seed changes everytime we run the program, it gives the illusion that we're getting random numbers.

If you want even a mild challenge, try doing the numbers 1 and 2: rand() % 2 + 1; and see how many times you can get it right, then try 1-5: rand() % 5 + 1.

You'll be surprised how hard it is to guess the right number.
I just started c++ and this forum. I am impressed how quickly I received feedback. Even more impressed on the magnitude of detail provided.

I did start with "random" numbers 1-2 to test it. It took 3 times for it to change to number 1 (I kept guessing 1).

I am not sure what these seeds are but lets face it. I don't know much about the programming world, Yet! =)

Thanks again.
The fun thing is when you get into basic AI that randomly chooses a spot on a tic-tac-toe board, or battleship, or even random moves in checkers. Seeding is more of a technical thing. One of those, you don't know why it works, but just know it does work.

And getting back to the error testing, I'd suggest just testing to make sure the user enters a number within range:
1
2
3
4
do {
    cout << "Enter a number (1-20): ";
    cin >> num;
}while (num < 1 || num > 20);


This will make it so the user is forced to guess a number within 1-20.

The same thing can be implemented at your yes/no area.

I don't know of a way to check if a user enters a character instead of a number aside from using strings, and that gets pretty complicated.
Last edited on
I tried it. It definitively motivates the user to pick one of the numbers within the range. If you pick a number outside the range it freezes. ha
It shouldn't freeze...I don't have my compiler in front of me so I can't test the code. I did forget to put the cin.ignore there, but that should cause it to freeze. Maybe once I get home I'll try it myself.
I may be putting it in the wrong spot.

I added an additional cout after I tested it. Trying to understand and fix it by trial and error.

*edit - I got it to work with giving the user one chance to pick a number within range. If you guess outside the range again it says "You guessed wrong"
* edit 2, It does recognize 1 and 10, Its just outputting my "wrong num" statement. Still have not fixed the the outside range numbers.

It doesn't recognize 1 or 10 though. I tried changing <, > to <=, >= but it freezes.



1
2
3
4
5
6
7
8
9
do { // Ensures the loop is run atleast once
        cout<<"\n Enter a number (1-10):  \n";
        cin>>num;
        // Ignore up to 256 characters after num, or until a line return
        cin.ignore(256, '\n');

        while (num < 1 || num > 10);
             cout<< "Number not within range. Pick number: (1-10)\n"; //erased
             cin>>num; //erased 
Last edited on
To do something like that, you want a while loop instead.
1
2
3
4
5
6
7
8
9
10
11
        cout<<"\n Enter a number (1-10):  \n";
        cin>>num;
        // Ignore up to 256 characters after num, or until a line return
        cin.ignore(256, '\n');

        while (num < 1 || num > 10) {
            cout<< "Number not within range. Pick number: (1-10)\n";
            cin>>num;
            // Ignore up to 256 characters after num, or until a line return
            cin.ignore(256, '\n');
        }


Edit: A good way to look at the difference between a while and do while is that a do while will display the same thing every time it loops, but a while loop will only display it's code "while" the conditions are met.

In this specific example, a do while would loop Enter a number (1-10): and wait for user input each time. This is great if you don't want to let the person know they entered an invalid number.

A while loop here would come after the original input, then you can error test, and inform the user they entered an invalid number, try again. That is exactly how the code above is working.

I use do whiles instead of declaring a variable, a lot of people find them annoying, for whatever reasons. With a while loop, you MUST define your variable before trying to assess it. In this case, you're using the num variable that was just defined by the user's input.
Last edited on
If I erase the do loop I cannot loop the play again. I get errors for:

while(playAgain == 'y' || playAgain == 'Y');

I think I am embarking on stuff beyond my skill This is fun. =D
Last edited on
your program would be contained within the do while like so:
1
2
3
4
5
do {
// Your program here
// ...
// More Lines
} while (playAgain == 'y' || playAgain == 'Y');


Don't forget the beginning do and opening bracket, and then the ending bracket, while, condition, and the semi colon. Stewbond's example of using just a while statement works just as well as using my do while if you find they're easier to use.
I got it work! I think I understand why.

It froze when I used:

while (num < 1 || num > 10)

But when I used the loop:
1
2
3
4
5
while (num < 1 || num > 10) {
            cout<< "Number not within range. Pick number: (1-10)\n";
            cin>>num;
            // Ignore up to 256 characters after num, or until a line return
            cin.ignore(256, '\n');


Without brackets it kept entering "Wrong number" because it was just a cout.

Adding brackets made it into a loop. Voiding "wrong number" unless it is a wrong number.

So if I understand correctly. Without the brackets (making it into a loop) the program wasn't sure what to do with a number out of range, so it froze.

When I enter any number or any combination of 11+ numbers (eg. 11111111111) when asked to enter a number it repeats wrong number. It locked up. End task wouldn't work. Had to go into the process tree to shut it down.

I should probably understand loops better before I push for these "strings" to counter the never ending "wrong number" when the user inputs a letter.

Thanks!
Last edited on
When you typed this, the compiler sees this:
1
2
while (num < 1 || num > 10)
   ;


If the code has to enter that while loop, it will indefinitely run [blank], which is what just a ; means, there is no statement.

Let's say you would have omitted the ; and had these lines
1
2
3
while (num < 1 || num > 10)
   cout << "You entered an invalid number";
cin >> num;


It would display You entered an invalid number forever since it only does one line. It never makes it to the cin.

Now with brackets, it does everything in those brackets as long as the condition is still met:
1
2
3
4
while (num < 1 || num > 10) {
   cout << "You entered an invalid number";
   cin >> num;
}


Notice the indentation, it should help you understand more about how things are run using brackets and not. Most IDEs support auto indent, and if for some reason it doesn't indent when you expect it to, then something might be wrong.
I started with Java a few weeks ago. I got to loops and realized Java has major limitations for what I want to do.

You mention indentations. Do indents and spaces effects C++?
They don't as far as I know in java.

I apologize for picking your brain so much. I understand one aspect then another question arises.
Pages: 12