Reputation:
I'm a beginner programmer in C++ trying to create this practice guess-the-number game that needs to fulfill some requirements. These are:
But the problem right now is that when I enter a number, it tells me whether the entered number is higher or lower than the randomly generated correct number continuously. So if it's lower, the output is 'lowerlowerlowerlowerlowerlowerlowerlowerlower' and so forth. I don't know what I did wrong?
Here is my code. (X = randomly generated number, Y = guess, Z = # of guesses)
int main() {
int x , y, z;
x = rand() % 1000 + 1;
std::cin>>y;
do{
if (y > x){
std::cout<<"higher"<< std::endl;
z++;
} else if (y < x) {
std::cout<<"lower"<< std::endl;
z++;
} else if (y == x) {
std::cout<<"correct"<< std::endl;
}
} while (y != x && z < 11);
return 0;
}
Upvotes: 0
Views: 115
Reputation: 97
You're doing wrong a few things:
std::cout << std::flush;
somewhere.z
variable to 0, because you've undefined behaviour - you're incrementing the variable which has undefined value (not initialized earlier).Here is your code with these fixes:
#include <iostream>
#include <ctime>
int main() {
int x, y, z = 0;
srand(time(NULL));
x = rand() % 1000 + 1;
std::cout << x << std::endl;
do {
std::cin >> y;
if(y > x) {
std::cout << "higher" << std::endl;
z++;
} else if(y < x) {
std::cout << "lower" << std::endl;
z++;
} else {
std::cout << "correct" << std::endl;
}
std::cout << std::flush;
} while(y != x && z <= 10);
return 0;
}
You said you don't know what is a flush operation. This is the operation of empting output buffer (used by std::cout object internally). Normally you don't need to explicitly flush output buffer, but if you need so...
Upvotes: 0
Reputation: 1697
srand (time(NULL)); // it will give 'x' every time a different value.
int z=0; // Dont forget to do this thing.
do{
cout<<"Enter number - "; // This thing your are missing.
std::cin>>y;
if (y > x){
std::cout<<"higher"<< std::endl;
z++;
}
else if (y < x) {
std::cout<<"lower"<< std::endl;
z++;
}
else if (y == x) {
std::cout<<"correct"<< std::endl;
}
} while (y != x && z < 11);
return 0;
Upvotes: 0
Reputation: 2795
Put your std::cin into the loop. You also need to set z at first and add it by 1 every time the loop runs.
int main() {
srand (time(NULL));
int x , y, z;
x = rand() % 1000 + 1;
z = 0;
do{
std::cin>>y;
if (y > x){
std::cout<<"higher"<< std::endl;
} else if (y < x) {
std::cout<<"lower"<< std::endl;
} else if (y == x) {
std::cout<<"correct"<< std::endl;
}
} while (y != x && z++ < 9);
return 0;
}
Upvotes: 1
Reputation: 7374
You have undefined behavior:
z++;
z
is used before initialization.
Upvotes: 0
Reputation: 2080
1- the variable z is not initialized
2-you are supposed to read the input everytime you loop i guess ( to read the guess )? like this
do{
std::cin>> y ;
// the rest of your loop
while(your condition);
Note : you should initialize random seed before you use your random function :
srand (time(NULL));
Upvotes: 0