Play Again Loop

Im 11 and im learning c++. For the last few hours I've been trying to make a number guessing game. I made it and all but I want to ask the user if he wants to play again. Ive been trying for hours looking at examples but my program isnt just working. (I don't want you to completely tell me the code, just explain)
Here is the code:


#include <iostream>
using namespace std;
int main()
{
srand(time(0));
int x =2+rand()%100;
int guess, YN;
cout << "I am thinking of a number bewteen 1-100. Can you guess it ?" << endl;
do {
cin >> guess;

if (x > guess)
{
cout << guess <<" is smaller than the number I am thinking of. Guess again" << endl;
}
else if (x <guess)
{
cout << guess <<" is larger than the number I am thinking of. Guess again" << endl;
}

else
{
cout << "That's it!"<< endl;
}
} while (guess != x);


system ("pause");
}
Last edited on
USE THE CODE TAGS


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
#include <iostream>
using namespace std;
int main()
{
srand(time(0));
int x =2+rand()%100;
int guess, YN;
cout << "I am thinking of a number bewteen 1-100. Can you guess it ?" << endl;
do {
cin >> guess; 

if (x > guess)
{
cout << guess <<" is smaller than the number I am thinking of. Guess again" << endl;
}
else if (x <guess)
{
cout << guess <<" is larger than the number I am thinking of. Guess again" << endl;
}

else
{
cout << "That's it!"<< endl; 
} 
} while (guess != x);


system ("pause");
}




Before I say anything on the answer:
- Attempt to rid of that system("pause") nonsense
- You don't need to type using namespace std; You're still new, so forget this one.


See the bottom of this post to find out why I gave the answer, and no hint.

The while(){} loop is extremely useful to you here. You can use values and test them continuously.
Instead of using cin >> x;, write: while(cin >> x) and finish it before your system("pause") statement.

The reason this works is simple: When you say while(cin >> x), you're actually saying: while(basic_istream& operator>> (int& x )). As you can imagine, this means that at runtime, the code can pick up the letter 'q' as input and terminate the loop.



The reason I pretty much gave the answer:
I'm tired, complain all you like.
Last edited on
Could you show how it would work on my specific code. Ive tryed using while statements but i dont know what im doing wrong. Im using system ("pause) because im using Dev-c++
Last edited on
and how do i use code tags
These are code tags:
[code]std::clog << "Learned how to use code tags!\n";[/code]

You can access them though the <> button to the right, under the word Format.

-Albatross
Last edited on
ty
Topic archived. No new replies allowed.