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;
}
#include <iostream>
usingnamespace 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;
}
elseif (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 usingnamespace 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.
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++