I need to do a Guessing game where the program generates a random number and the user has to guess the number. If the user guesses the number in less than 10 guesses the program congratulates them and lets them know they were under 10 guesses. If they were above 10 guesses then it lets them know it was above 10, etc.
The problem I'm facing is if, for example, the user guesses the number in 3 tries and then decides to play again with a whole new other number, and this time guesses it in 8 tries, instead of still congratulating them because it was under 10 tries, it counts the 3 tries from the previous game. This then leads the program to tell them they were over 10 tries, even though they were not. I don't know how to fix this. The code I've done so far is as follows:
int main()
{
srand(time(0));
int guess;
int number;
char selection = 'y';
int numberOfGuesses=0;
while(selection == 'y' || selection == 'Y')
{
number = rand() % 1000 + 1;
cout << "I have a number between 1 and 1000.\nCan you guess my number?\nPlease type your first guess: ";
cin >>guess;
do
{
if(number > guess)
{
cout << "Too low. Try again: " << endl;
cin >> guess;
numberOfGuesses++;
}
if (number < guess)
{
cout << "Too high. Try again: " << endl;
cin >> guess;
numberOfGuesses++;
}
}
while(number != guess);
if(numberOfGuesses < 9)
{
cout << "You guessed the number in less than 10 guesses!\n Would you like to play again (y or n)?";
cin >> selection;
}
else if(numberOfGuesses > 9)
{
cout << "You guessed the number\n Would you like to play again (y or n)?";
cin >> selection;
}
else if(numberOfGuesses == 9)
{
cout << "You guessed the number.\n Would you like to play again (y or n)?";
cin >> selection;
}
}
return 0;
}
The problem is that you are not resetting the counter.
Just put int numberOfGuesses=0; within the while loop:
while(selection == 'y' || selection == 'Y')
{
int numberOfGuesses=0;
....
}
You need to set numberOfGuesses to 0 before every game. Your program only sets it once when the program first launched.
You are not resetting numberOfGuesses to zero after each round. You can solve the problem using one of couple of methods.
Reset the value of numberOfGuesses to zero at the end of the first while loop.
while(selection == 'y' || selection == 'Y')
{
...
numberOfGuesses = 0;
}
Don't define the variable until the start of that while loop. Define it as the first statement and initialize it zero.
while(selection == 'y' || selection == 'Y')
{
int numberOfGuesses = 0;
...
}
Related
I am writing a program, the program is basically a guessing game. Computer displays a number and the user has to guess whether their number is higher, lower or correct. I have already made the program and its all dandy, but the only not dandy part is that I cannot figure out how to get rid of the input buffer when the user decides to play the game again. Every time the user wants to play the game, the game starts again but with the same input as the last game. I have tried putting cin.clear() in any spot I could think and also cin.clear(). But it just seems to not work. How do I clear the input?
#include <iostream>
using namespace std;
int main ()
{
int num1 = 100;
char choice;
num1 = num1 / 2;
do
{
cout << "My guess is " << num1 << ". " << "Enter 'l' if your number is lower, 'h' if it is higher, 'c' if it is correct: ";
cin >> choice;
cin.clear();
if (choice == 'h')
{
num1 = num1 + 100;
num1 = num1 / 2;
}
if (choice == 'l')
{
num1 = num1 + num1;
num1 = num1 - 11;
num1 = num1 / 2;
}
if (choice == 'c')
{
cout << "Great! Do you want to play again (y/n)?: ";
cin >> choice;
}
} while (choice != 'c' || choice == 'Y' || choice == 'y' || choice == 'n' || choice == 'N');
return 0;
}
In order to restart the game, you need to reset num1. Put the inital value in a variable that you don't change.
const int init = 100;
char choice;
int num1 = init / 2;
When the computer has guessed correctly:
if (choice == 'c')
{
num1 = init / 2; // reset
cout << "Great! Do you want to play again (y/n)?: ";
cin >> choice;
}
You could also leave the loop condition at:
} while(choice != 'N' && choice != 'n');
You should also work on the divide and conquer algorithm. For the computer to be effective, it should always make a guess in the middle of the range that is still possible, and that's not what it's doing right now. It jumps up and down, even outside the established range. An alternative could be to keep two variables to be able to shrink the possible range effectively. You could also do two separate loops, one inner loop for guessing the number and one outer that only asks the user if he/she wants to play again.
Example:
#include <iostream>
int main() {
const int initlo = 1;
const int inithi = 100;
char choice;
do {
std::cout << "Think of a number [" << initlo << "," << inithi << "]\n";
int numlo = initlo; // initialize the range
int numhi = inithi;
int guess;
do {
guess = (numlo + numhi) / 2; // guess in the middle of the range
std::cout
<< "My guess is " << guess << ". "
<< "Enter 'l' if your number is lower, 'h' if it is higher, 'c' "
"if it is correct: ";
std::cin >> choice;
if(choice == 'h') // must be in the range (guess,numhi]
numlo = guess + 1;
else if(choice == 'l') // must be in the range [numlo,guess)
numhi = guess - 1;
// exit the loop if the user cheats or the answer is correct
} while(numlo <= numhi && choice != 'c');
if(choice == 'c') std::cout << "Great! ";
else std::cout << "Cheater! ";
std::cout << "Do you want to play again (y/n)?: ";
std::cin >> choice;
} while(choice == 'Y' || choice == 'y');
std::cout << "Bye\n";
}
I'm new to stackoverflow, and also somewhat new to programming, so please don't mind my poor formatting of the code. I have two problems with my code.
My continue statement, which I'm using to continue the loop if the player types 'y' or 'Y', doesn't work. It terminates the program after only getting the guess correctly, which leads me to:
2.My continue counter goes past 0 without stopping, and I just can't see my error in the logic of the program.
I can't see the problems with my logic.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <ctime>
#include <random>
using namespace std;
int getNumber(); //random number prototype
double getScore(); //gets score
int chances = 7; //chances to guess with
int main()
{
int guess = 0,
random;
char retry = 'y'; //initialize retry to 'y'
cout << "This is a random number guessing game. " << "You will be guessing between 1-100."
<< "You have 7 chances. Good luck! \n \n" << endl;
random = getNumber(); //give the function a variable
do
{
cout << random << "\n" << "\n";
chances--;
cout << "Enter your guess: ";
cin >> guess;
if (guess == random)
{
cout << "You have won the game! " << "Your score was: " << getScore();
cout << "Would you like to retry? (Y or N): ";
cin >> retry;
if (retry == 'y' || retry == 'Y')
{
chances = 7;
guess = 0;
getNumber();
continue; //player can retry the game
}
else if (chances == 0)
{
cout << "You have no chances left. Retry? (Y or N): ";
cin >> retry;
if (retry == 'y' || retry == 'Y')
{
chances = 7;
guess = 0;
getNumber();
continue;
}
}
return 0;
}
else if (guess != random)
cout << "You got it wrong. \n" << "You have: " << chances << " chances left" << endl << endl;
else
cout << "Incorrect Input. Please type a number." << endl << endl;
} while (guess != random);
return 0;
}
int getNumber()
{
unsigned seed = time(0); //seed the random number
srand(seed);
int randNum = rand() % 10 + 1; //random number in the range of 1-10
return randNum;
}
if (retry == 'y' || 'Y')
This is incorrect logic, which is why your code does not work the way you want it to. You want it to be:
if (retry == 'y' || retry == 'Y')
Fix this logic error in your other if-else statements as well.
You'll wanna take a look at this
Your continue statement is jumping to the end and checking the condition, guess != random, which evaluates to false and exits the do while. What you need to do is reset guess to a value such as 0 so that the condition does evaluate to true.
My homework is to write a program that finds the highest, lowest, and average of 5 numbers in an Array that the user inputs. Here is my problem, the user does not have to enter all 5 numbers. But has to enter at least 2 numbers minimum.
I have the whole program done already I am having a problem with the beginning, below is my code where I am having a problem:
// Ask for name and explain program
cout << "Please enter your name: ";
cin >> name;
cout << endl;
cout << "Hi " << name << ", please enter up to 5 whole numbers." << endl;
cout << "I will find the HIGHEST, LOWEST, and AVERAGE number." << endl;
// Loop through users input
for (int i = 0; i < SIZE; i++)
{
cout << "Enter number " << (i + 1) << " : ";
cin >> number[i];
// Validate that the user has entered atleast 2 numbers
if (i >= 1 && i < 4)
{
cout << "Do you wish to enter another number (Y/N)? : ";
cin >> continue_game;
// Validate that the user only enters Y/N
while (continue_game != 'Y' && continue_game != 'y' && continue_game != 'N' && continue_game != 'n')
{
cout << "Please type in (Y/N): ";
cin >> continue_game;
}
// What happens if user chooses NO
if (continue_game == 'N' || continue_game == 'n')
{
i = 5;
}
// What happens if user chooses YES
else if (continue_game == 'Y' || continue_game == 'y')
{
i = i;
}
}
}
PROBLEM: If the user presses no after the 2nd number the remaining elements get a number asigned to them like : -8251616. Is there any way to make sure that the elements get assigned a zero or stay blank please help its due tomorrow and I can not figure it out.
SIZE = 5
Don't set i = 5 when the user says no. Just end the loop with a break; statement.
Also, the i = i; statement in the yes case is useless.
When you're getting the highest, lowest, and average values, make sure you only look at the values from 0 to i-1, so you don't access the uninitialized elemends of the array.
If you really want zeros you need to fill array with zeros:
int number[5] = {};
or
int number[5];
for (int i = 0; i < 5; ++i) {
number[i] = 0;
}
However this will give wrong output if the user enter less than 5 numbers. What you should do is to count how many numbers user entered and then use values from 0 to count - 1.
Advice, use break; instead of i = 5;.
I am just a newbie to programming and I was trying to write a while loop that runs as long as the input (num) is not a integer which doesn't ends with zero. What happen is when I enter a number that ends with zero, the program runs the loop correctly, but when i enter something nonsense such as rofl the program only print The input is not valid. and won't repeat the loop. I have tried to look for solutions but I am still stuck after a hour. Anyone can help me here? Thx so much!
void rev_sum() {
int num;
int a = 1;
while (a < 2) {
cout << "Please input a natural number without zero at the end:\n";
cin >> num;
if (!cin) {
cout << "The input is not valid.\n";
cin.clear();
cin.ignore(INT_MAX);
}
if (num % 10 == 0) {
cout << "The number cannot have zero at the end\n";
} else {
cout << "gj\n";
break;
}
}
}
Try replacing
cin.ignore(INT_MAX);
With
cin.ignore(numeric_limits<streamsize>::max(), '\n');
And change the
if (num % 10 == 0)
To
else if (num % 10 == 0)
Your final code should look like this:
void rev_sum() {
int num;
int a = 1;
while (a < 2) {
cout << "Please input a natural number without zero at the end:\n";
cin >> num;
if (!cin) {
cout << "The input is not valid.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else if (num % 10 == 0) {
cout << "The number cannot have zero at the end\n";
} else {
cout << "gj\n";
break;
}
}
}
if (num % 10 == 0) {
could be
else if (num % 10 == 0) {
otherwise the other else case might get executed
You set a = 1 at the start of the loop and then never change a which means the only way to leave your while loop is if you hit the break statement. If your loop is not looping then it must be stuck somewhere. I'm unfamiliar with the statements if (!cin) and cin.ignore(...) so those are top suspects to check (or change). The statement cin >> num; completes no matter what they type so you can check to see what 'num' is equal to when you enter "rofl". Then after it fails, you still use num so you are processing this unintentional entry. You can add continue; after cin.ignore(...) to jump back to the top of the while loop and ask the question again. You can also print something after the while loop in order to know when you get out.
With all that said, I would never trust the user to enter acceptable information and I would never trust cin to process it for me. Personally, I would read cin as a string using cin.getline(buffer, buffer_size); And then I would complain to the user if they filled the buffer or gave me something that was not an integer (which you can check with a function like scanf()). Then you can spit back exactly what they gave you and you can be specific about your complaint.
Would it not make more sense to only check that the number ends in 0 if the input was valid....
void rev_sum() {
int num;
int a = 1;
while (a < 2) {
cout << "Please input a natural number without zero at the end:\n";
cin >> num;
if (!cin) {
cout << "The input is not valid.\n";
cin.clear();
cin.ignore(INT_MAX);
} else {
if (num % 10 == 0) {
cout << "The number cannot have zero at the end\n";
} else {
cout << "gj\n";
break;
}
}
}
}
cin.ignore(numeric_limits<streamsize>::max())
I think the question speaks for itself, I'm writing a program in c++ and there is a part where the console asks the user which type of input they want to use
while (loop == 5) {
cout << "\nWould you like to enter a depoist or a check? "; //asks for a choice
cin >> choice;
//determines whether or not to close the program
if(choice == 0 || depo == 0 || check == 0) {
return 0;
}//end close if
//choses which type of input to make
if( choice == 1) {
cout << "\nPlease enter check amount: ";
cin >> check;
check += check;
} else if(choice == 2) {
cout << "\nPlease enter deposit amount: ";
cin >> depo;
depo += depo;
}//end if
}
but how do i keep track of how many times the if statement was true?
You can add a counter and increment it every time you enter the if-statement's true block.
int true_counts = 0;
while (loop == 5){
...
if( choice == 1){
true_counts++;
...