C++ Homework Doesn't Loop - c++

So, I'm super new to C++ and am sharing a book with a friend. I'm creating a simple guessing game, where the user imagines a number, and the computer attempts to guess it. When I debug in Visual Studio, the project does make a guess, and properly prints "how did I do?". At this point, it should get user input for the 'feedback' variable. After the prompt, however, it seems as if it will only repeat everything before the 'while' statement. Does the problem concern the feedback char variable (maybe I should've just used 'cin' and integers?), or am I just missing something really obvious?
//Game that attempts to guess a number from one to twenty.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
auto lowbound = 1;
auto highbound = 20;
auto guess = 10;
auto gamecont = true;
char feedback[1];
cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << endl << endl;
cout << " If my guess is too low, just say (1). If too high, say (2). Say (3) if I've got it. It's (ENTER) to get going!" << endl << endl;
cout << " Waiting on you..." << endl << " ";
cin.get();
while(gamecont)
{
cout << " I'm thinking your number is " << guess << "." << endl << endl;
cout << " How did I do?" << endl << endl << " ";
cin.get(feedback, 1);
if (feedback[1] == 1) // The guess was too low.
{
if (guess == 10)
{
guess = 15;
}
else if (guess >= 15)
{
guess++;
}
else if (guess < 10)
{
guess++;
}
}
else if (feedback[1] == 2) // The guess was too high.
{
if (guess == 10)
{
guess = 5;
}
else if (guess <= 5)
{
guess--;
}
else if (guess > 10)
{
guess--;
}
}
else if (feedback[1] == 3) // The guess was correct.
{
gamecont = false;
}
}
return 0;
}
Sorry if this question is stupid for whatever reason, and thanks in advance for reading.

a journey of a thousand miles begins with a single step, so here´s some aid for your first step:
using namespace std;
don´t do that. std:: is crowded with identifiers you might use too, problems are guaranteed.
char feedback[1];
You´ll never have input longer than 1, so
char feedback;
is more than appropriate. (besides: arrays are 0 based so it should have been char feedback[0]; instead of char feedback[1];)
cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << endl << endl;
std::endl flushes the buffer, no need to do that twice. Simply use '\n':
std::cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << "\n\n";
you´ll get the character code of the key in feedback. '1' is not equal to 1, so
if (feedback == 1)
should be
if (feedback == '1')
Thats it. There still some work remaining to do for you, e.g. the guessing strategy is poor, but that should be a start.
//Game that attempts to guess a number from one to twenty.
#include <iostream>
int main()
{
auto lowbound = 1;
auto highbound = 20;
auto guess = 10;
auto gamecont = true;
char feedback;
std::cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << "\n\n";
std::cout << " If my guess is too low, just say (1). If too high, say (2). Say (3) if I've got it. It's (ENTER) to get going!" << "\n\n";
std::cout << " Waiting on you..." << "\n\n";
std::cin.get();
while(gamecont)
{
std::cout << " I'm thinking your number is " << guess << "." << "\n\n";
std::cout << " How did I do?" << "\n\n";
std::cin.ignore();
std::cin.get(feedback);
if (feedback == '1') // The guess was too low.
{
if (guess == 10)
{
guess = 15;
}
else if (guess >= 15)
{
guess++;
}
else if (guess < 10)
{
guess++;
}
}
else if (feedback == '2') // The guess was too high.
{
if (guess == 10)
{
guess = 5;
}
else if (guess <= 5)
{
guess--;
}
else if (guess > 10)
{
guess--;
}
}
else if (feedback == '3') // The guess was correct.
{
gamecont = false;
}
}
return 0;
}

Related

Can I make this more efficient with loop?

if(diff != 0){
if(diff >= 50){
if(userGuess > toGuess){
cout << "Very high" << endl;
} else if (userGuess < toGuess){
cout << "Very low" << endl;
}
}
if(diff >= 30 && diff < 50){
if(userGuess > toGuess){
cout << "high" << endl;
} else if (userGuess < toGuess){
cout << "low" << endl;
}
}
if(diff >= 15 && diff < 30){
if(userGuess > toGuess){
cout << "Moderately high" << endl;
} else if (userGuess < toGuess){
cout << "Moderately low" << endl;
}
}
if(diff > 0 && diff < 15){
if(userGuess > toGuess){
cout << "Somewhat high" << endl;
} else if (userGuess < toGuess){
cout << "Somewhat low" << endl;
}
}
}
These if statement are in loops that run until the correct number is guessed, my question is, instead of having all these if statements can I make it better with a big loop.
You can certainly make it more readable, the approach is to make more functions and to group things together. And then you can do all your tests in a loop.
(You might want to refine the logic for negative numbers, I didn't test the correctness of all corner cases for you)
For example :
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <limits>
// group all information to be able to give a hint in one struct
struct hint
{
bool in_range(int v) const noexcept
{
return (v>= min) && (v< max);
}
int min;
int max;
std::string_view output;
};
// then make a function that will return the correct hint
// for a given difference value
std::string_view get_hint(const int dif)
{
// instead of having a global variable I use a static local variable, this is initialized only once.
// use initializer list to initialize all hint structures
static std::vector<hint> hints
{
{50,std::numeric_limits<int>::max(),"very high"},
{30,50,"high"},
{15,30,"moderately high"},
{0,15, "somewhat high" },
{-15,0, "somewhat low" },
{-30,-15, "moderately low"},
{-50,-30, "low"},
{std::numeric_limits<int>::min(), -50, "very low"}
};
// check which hint text to return
// This is the part where a loop helps
for (const auto& hint : hints)
{
if (hint.in_range(dif)) return hint.output;
}
return {};
};
int main()
{
std::cout << get_hint(-1) << "\n";
std::cout << get_hint(49) << "\n";
std::cout << get_hint(50) << "\n";
std::cout << get_hint(-17)<< "\n";
return 0;
}
The main lesson here is that the compiler will almost always outsmart you and do it the fastest way it knows how. The code you have posted seems extremely unlikely to have any meaningful impact on the speed of your program.
Instead, it is often better to choose an approach which makes your code easier to read and maintain. For example, you could try something like this:
// Add size prefix based on difference
if (diff > 50) {
cout << "Very ";
} else if (diff >= 30) {
// No prefix
} else if (diff >= 15) {
cout << "Moderatly ";
} else {
cout << "Somewhat ";
}
// State if code was low or high
if (userGuess > toGuess) {
cout << "high" << endl;
} else {
cout << "low" << endl;
}

Can someone help me figure out why my code isn't working properly?

#include <iostream>
using namespace std;
int fight();
int lowblow();
int eyes();
int run();
int underground();
int officebuilding();
int main()
{
int choice1;
int fchoice2, fchoice3;
int rchoice2, rchoice3;
cout << "As you’re walking down the street you feel somebody grab your shoulder, when you turn around to see. You notice the person is holding a knife towards you and demanding for your valuables." << endl;
cout << "Do you fight or run?" << endl;
cout << "1 - Fight" << endl;
cout << "2 - Run" << endl;
cin >> choice1;
while (choice1 != 1 && choice1 != 2) {
cout << "Do you fight or run? " << endl;
cout << "1 - Fight" << endl;
cout << "2 - Run" << endl;
cin >> choice1;
}
if (choice1 == 1) {
fchoice2 = fight();
while (fchoice2 != 1 && fchoice2 != 2) {
fchoice2 = fight();
}
if (fchoice2 == 1) {
fchoice3 = lowblow();
while (fchoice3 != 1 && fchoice3 != 2) {
fchoice3 = lowblow();
}
}
if (fchoice2 == 2) {
fchoice3 = eyes();
while (fchoice3 != 1 && fchoice3 != 2) {
fchoice3 = eyes();
}
if (choice1 == 2) {
rchoice2 = run();
while (rchoice2 != 1 && rchoice2 != 2) {
rchoice2 = run();
}
if (rchoice2 == 1) {
rchoice3 = underground();
while (rchoice3 != 1 && rchoice3 != 2) {
rchoice3 = underground();
}
if (rchoice3 == 1) {
officebuilding();
}
}
}
}
}
}
int fight()
{
system("clear");
int c2;
cout << "You choose to fight off the attacker and suddenly all those self-defense classes come rushing into your mind.As you fight to defend yourself, you find yourself getting outmatched and have to try something drastic to survive." << endl;
cout << "1 - Go for the low blow" << endl;
cout << "2 - Go for the eyes " << endl;
cin >> c2;
return c2;
}
int lowblow()
{
system("clear");
cout << "You catch your attacker off guard and land the hit, to your surprise the attack proves ineffective.In retaliation you get hit so hard that you start seeing stars and soon blackout leaves you defenseless.Now you are knocked out and getting your valuables taken." < endl;
cout << "The End" << endl;
return 0;
}
int eyes()
{
system("clear");
cout << "Using the element of surprise to try fighting back gave you no advantage, so you resort to another tactic. You’ve seen it in movies and it always worked out there. You decide to go for the eyes and to your surprise it works. You use this opportunity to escape and get to safety, all while keeping your valuables safe. "<< endl;
cout << "The End" << endl;
return 0;
}
int run()
{
system("clear");
int c2;
cout << " While running down the street to loose the attacker, you noticed that there was an underground subway a little down the road.Immediately to your left there is an office building you could run into and try to lose your attacker there."<< endl;
cout << "1 - Underground ?" << endl;
cout << "2- office building?" << endl;
cin >> c2;
return c2;
}
int underground()
{
system("clear");
cout << "As you make your way towards the underground subway station you notice rushing out.In a desperate attempt to reach safety, you run down the stairs while narrowly avoiding others.Upon arriving at the station you look back and notice that you lost your attacker.You are safe now.";
cout << "The End" << endl;
return 0;
}
int officebuilding()
{
system("clear");
cout << "A spontaneous decision leads you into an office building, while it may look safe, upon entering you notice everything is silent as the building seems to be completely empty.None of it matters however, since you have to escape at any cost in order.While trying to find a good way to lose the attacker you hear footsteps behind you.The attacker has cornered you and has taken your valuables." << endl;
cout << "The End" << endl;
return 0;
}
I am suppose to be writing a branching-path story. I am not sure why after I pick a choice it starts flashing and for the other choice it isn't even working. I'm not exactly sure where to fix these errors in the code. I'm not sure if I messed up somewhere in the functions or while loop. I've tried changing some things around but nothing seems to work.
You are calling underground() in a while-loop waiting for rchoice3 to be 1 or 2, but underground() always returns 0, so rchoice3 is always 0..
while (rchoice3 != 1 && rchoice3 != 2) {
rchoice3 = underground();
}
I think you need to change this block:
if (rchoice2 == 1) {
rchoice3 = underground();
while (rchoice3 != 1 && rchoice3 != 2) {
rchoice3 = underground();
}
if (rchoice3 == 1) {
officebuilding();
}
}
To:
if (rchoice2 == 1) {
underground();
} else {
officebuilding();
}

How do I make the code not repeat

int main() {
power=1;
while (1 == 1){
tapcost=power*3;
cout << "type upgrade/buy/a" << endl;
cin >> way;
if (way == "upgrade"){
cout << "1. A Power " << "(Costs: " << tapcost << ")" << endl;
cin >> upgr;
if (upgr == 1){
if (0<=money-power*3){
power=power+1;
money=money-power*3;
}
else
cout << "You can't afford that!!!" << endl;
}
}
if (way == "a"){
money=money+power;
}
}
return 0;
}
When I type upgrade and then type anything else other than the variable "1", the code will repeat infinitely.
This is a never-ending problem.
See this question: Infinite loop with cin when typing string while a number is expected
I think your code have some mistakes.
int upgr;
cin >> upgr; // you can type any number you want (-2 147 483 648 / 2 147 483 647)
I suggest you to use getline, cin.getline or fgets instead of cin >> when reading a line.
And just use while(1) or while(true)
You have created an infinite loop by never changing the value of your ‘1’ variable. In some way you need to change that value when iterating through your conditions or else you’ll never get out of your loop.
You could also try out something like that.
char i;
while((std::cin >> i) && i != '1') {
....
}
In your code, while (1 == 1) creates an infinite loop. Since I assume you want this code to keep asking players for their input until they decide to stop, you can add an option exit which breaks out of the loop when the player wants to.
#include <iostream>
int main() {
int power = 1;
int money = 1000;
while (1 == 1) {
int tapcost = power * 3;
std::string way;
std::cout << "type upgrade/buy/a/exit" << std::endl;
std::cin >> way;
if (way == "upgrade") {
std::cout << "1. A Power " << "(Costs: " << tapcost << ")" << std::endl;
int upgr;
std::cin >> upgr;
if (upgr == 1) {
if (0 <= money - power * 3) {
power = power + 1;
money = money - power * 3;
}
else {
std::cout << "You can't afford that!!!" << std::endl;
}
}
}
if (way == "a") {
money = money + power;
}
if (way == "exit") {
break;
}
}
return 0;
}

Jumping into c++ chapter 5 prob 7

as recommended I've been working through the book 'Jumping into c++'. I'm currently on problem 7 of chapter 5 and although I have produced the code that appears to do what is asked of me I was hoping someone might be able to take a look and tell me if I've implemented any 'bad' practice (Ideally I don't want to be picking up bad habits already).
Secondly, it also says 'try making a bar graph that shows the results properly scaled to fit on your screen no matter how many results were entered'. Again, the code below produces a horizontal bar graph but I'm not convinced that if I had say 10000 entries (I guess I could verify this by adding an additional for loop) that it would scale according. How would one go about applying this? (such that it always properly scales regardless of how many entries).
I should probably point out at this point that I have not covered topics such as arrays, pointers and classes as of yet in case anyone was curious as to why I didn't just create a class called 'vote' or something.
One final thing... I don't have a 'return 0' in my code, is this a problem? I find it slightly confusing as to what exactly the point of having return 0 is. I know that it's to do with making sure your code is running properly but it seems sort of redundant?
Thanks in advance!
#include <iostream>
using namespace std;
int main()
{
int option;
int option_1 = 0;
int option_2 = 0;
int option_3 = 0;
cout << "Which is your favourite sport?" << endl;
cout << "Tennis.. 1" << endl;
cout << "Football.. 2" << endl;
cout << "Cricket.. 3" << endl;
cin >> option;
while(option != 0)
{
if(option == 1)
{
option_1++;
}
else if(option ==2)
{
option_2++;
}
else if(option ==3)
{
option_3++;
}
else if(option > 3 || option < 0)
{
cout << "Not a valid entry, please enter again" << endl;
}
else if(option ==0)
{
break;
}
cout << "Which is your favourite sport?" << endl;
cout << "Tennis.. 1" << endl;
cout << "Football.. 2" << endl;
cout << "Cricket.. 3" << endl;
cin >> option;
}
cout << "Option 1 (" << option_1 << "): ";
for(int i = 0; i < option_1; i++)
{
cout << "*";
}
cout << "" << endl;
cout << "Option 2 (" << option_2 << "): ";
for(int i = 0; i < option_2; i++)
{
cout << "*";
}
cout << "" << endl;
cout << "Option 3 (" << option_3 << "): ";
for(int i = 0; i < option_3; i++)
{
cout << "*";
}
}
About the return 0 in main : it's optional in C++.
About your code:
You have a ton of if / else if blocks, you should replace them with a switch. A switch statement is more compact, readable, and may be a little bit faster at runtime. It's not important at this point, but it's pretty good practice to know where to put a switch and where to use regular if.
You have one big function, it's really bad. You should break your code into small, reusable pieces. That's something called DRY (Don't repeat Yourself): if you are copy-pasting code, you're doing something wrong. For example, your sport list appears 2 times in your code, you should move it in a separate function.
You wrote cout << "" << endl;, I think you don't really understand how std::cout work. std::cout is an object representing the standard output of your program. You can use operator<< to pass values to this standard output. std::endl is one of these values you can pass, strings are, too. So you can just write cout << endl;, no need for an empty string.
Please learn how to use arrays, either raw ones or std::array. This is a pretty good example of a program which can be refactored using arrays.
Here is a more readable, cleaner version of your code:
#include <iostream>
int prompt_option()
{
int option;
while (true)
{
std::cout << "Which is your favourite sport?" << std::endl;
std::cout << "Tennis.. 1" << std::endl;
std::cout << "Football.. 2" << std::endl;
std::cout << "Cricket.. 3" << std::endl;
std::cin >> option;
if (option >= 0 && option <= 3)
return option;
else
std::cout << "Not a valid entry, please enter again" << std::endl;
}
}
void display_option(int number, int value)
{
std::cout << "Option " << number << " (" << value << "): ";
while (value--)
std::cout << '*';
std::cout << std::endl;
}
int main()
{
int option;
int values[3] = {0};
while (true)
{
option = prompt_option();
if (option)
values[option - 1]++;
else
break;
}
for (int i = 0; i < 3; i++)
display_option(i + 1, values[i]);
}
You have too much if else, it messy.
check out the code bellow, muc shorter, cleaner and efficent.
I hope it helps.
#include <iostream>
using namespace std;
int main()
{
int choice;
int soccer=0, NFL=0 ,formula1=0;
while(choice != 0){
cout<<"Please choose one of the following for the poll"<<endl;
cout<<"press 1 for soccer, press 2 for NFL, press 3 for formula 1"<<endl;
cout<<"Press 0 to exit"<<endl;
cin>>choice;
if(choice==1){
soccer++;
}
else if(choice==2){
NFL++;
}
else if(choice == 3){
formula1++;
}
else{
cout<<"Invalid entry, try again"<<endl;
}
cout<<"soccer chosen "<<soccer<<" times.";
for(int i=0; i<soccer; i++){
cout<<"*";
}
cout<<endl;
cout<<"NFL chosen "<<NFL<<" times.";
for(int j=0; j<NFL; j++){
cout<<"*";
}
cout<<endl;
cout<<"formula1 chosen "<<formula1<<" times.";
for(int c=0; c<formula1; c++){
cout<<"*";
}
cout<<endl;
}
return 0;
}

I've know idea where to look, maybe it's an infinite loop? (C++, using VS2012) [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Well, I'll introduce myself first. I'm Ben, a 17-years old 'game-programmer' from the Netherlands who just has begun to program in C++ (started about a month ago, but programming for a year right now) (and I'm using Microsoft Visual Studio 2012 as compiler). Now, I am 'learning it myself' but I still do use a book and that book is called 'Beginning C++ Through Game Programming, Third Edition' by Michael Dawson.
I just did finish with chapter two and the last excersize was: "Write a new version of the Guess My Number program in which the player and the computer switch roles. That is, the player picks a number and the computer must guess what it is."
Here follows the code of the 'Guess My Number' Program:
// Guess My Number
// The classic number guessing game
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0))); //seed random number generator
int secretNumber = rand() % 100 + 1; // random number between 1 and 100
int tries = 0;
int guess;
cout << "\tWelcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
if (guess > secretNumber)
{
cout << "Too high!\n\n";
}
else if (guess < secretNumber)
{
cout << "Too low!\n\n";
}
else
{
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
}
} while (guess != secretNumber);
return 0;
}
Now, I was busy with thinking, programming testing and it just wouldn't work.
It seems I got stuck with such a infinite loop. But I can't find the problem.
Here's the code, and other ways to fix this are welcome, just keep in mind that I don't know a lot of the language. ;)
// Guess My Number 2
// The classic number guessing game with a twist
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
int secretNumberComputer = rand() % 100 + 1;
int secretNumberPlayer;
int triesPlayer = 0;
int triesComputer = 0;
int guessPlayer;
int guessComputer;
int tooHighPlayer;
int tooLowPlayer;
int correctPlayer;
int tooHighComputer;
int tooLowComputer;
int correctComputer;
int selectNumberIncorrect;
int lowerGuessComputer = 101;
int higherGuessComputer = 0;
cout << "Welcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guessPlayer;
++triesPlayer;
tooHighPlayer = (guessPlayer > secretNumberComputer);
tooLowPlayer = (guessPlayer < secretNumberComputer);
correctPlayer = (guessPlayer == secretNumberComputer);
if (tooHighPlayer)
{
cout << "Too high!\n\n";
}
else if (tooLowPlayer)
{
cout << "Too low!\n\n";
}
else if (correctPlayer)
{
cout << "\nThat's it! You got it in " << triesPlayer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctPlayer);
cout << "Now it's time for you to pick a number and then the computer will guess.\nEnter a number between 1 and 100: ";
do
{
cin >> secretNumberPlayer;
selectNumberIncorrect = (secretNumberPlayer > 100 || secretNumberPlayer < 1);
if (selectNumberIncorrect)
{
cout << "\nHey, that isn't a number between 1 and 100! Please pick a number that is: ";
}
else
{
break;
}
} while (selectNumberIncorrect);
guessComputer = (rand() < lowerGuessComputer && rand() > higherGuessComputer);
cout << "\n\nNow the computer is going to try to guess your number:" << endl;
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
tooHighComputer = (guessComputer > secretNumberPlayer);
tooLowComputer = (guessComputer < secretNumberPlayer);
correctComputer = (guessComputer == secretNumberPlayer);
lowerGuessComputer = (rand() % 100 + 1 && rand() < guessComputer);
higherGuessComputer = (rand() % 100 + 1 && rand() > guessComputer);
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
}
else
{
cout << "Error, check code!\n\n";
}
do
{
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctComputer);
if (triesComputer < triesPlayer)
{
cout << "You lost against the computer!\n\n";
}
else if (triesComputer > triesPlayer)
{
cout << "You won!\n\n";
}
else
{
cout << "It's a tie!\n\n";
}
cout << "Thank you for playing! Goodbye!" << endl;
return 0;
}
In this block you aren't checking the computer's guess for correctness (assigning correctComputer), so the loop continues forever, unless it guessed correctly the first time.
do
{
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctComputer);
Your second do loop never recalculates the computer's guess.
i.e. you have the computer guess one number before the do loop, then in the loop you keep checking if that one guess is too high or too low, never recalculating its value. It'll obviously never end.
You need to do the computer's guess calculation inside the second loop.
EDIT
Also, this logic is incorrect:
lowerGuessComputer = (rand() % 100 + 1 && rand() < guessComputer);
higherGuessComputer = (rand() % 100 + 1 && rand() > guessComputer);
The guess will always be 0 or 1 because the result of the right-hand-side operation is a boolean. In fact, I don't know what you're trying to do there. You're performing && between an integer and a boolean. I also don't understand why you are calculating two different guesses - you should calculate one number within the range of the higher/lower parameters you were given.
In addition to what Kevin Tran wrote, please check the valid input type for cin.
Imagine someone typing characters instead of integers.
so
cin >> guessPlayer;
can be written as
if (cin >> guessPlayer) {
// Do you logic here
}
else {
cout<<"Enter numbers only. :)";endl;
continue;
}
Hope this helps.
Instead of analyzing the code you posted which has numerous flaws, let's just think about what your program has to do: The user will pick a random number, and the computer will try to guess that number.
So, your program flow should go like this:
The computer picks a random number. It prints it out and asks the user to choose if the number is too high, too low or correct. (i.e. by asking the user to type '1' if too high, '2' if too low or '3' if it's right).
If the user types '3' then obviously you're done.
If it's too high, the computer picks a new random number (smaller than it's last guess) and tries the above logic again.
If it's too low, the computer picks a new random number (greater than it's last guess) and tries the above logic again.
Now let's try and implement some code that implements the above:
using namespace std;
int main()
{
int range_low = 0; // The number the user picked is greater than this
int range_high = 100; // The number the user picked is smaller than this
srand(static_cast<unsigned int>(time(0)));
do
{
// We want to generate a random number between range_low and range_high. We do this
// by generating a random number between zero and the difference of "low" and "high"
// adding it to low and adding one more.
int guess = range_low + ((rand() % (range_high - range_low)) + 1);
cout << "I'm guessing your number is " << guess << "... how did I do?" << endl
<< " [1: too high, 2: too low, 3: you got it!] ";
// Now let's see how we did...
int choice;
cin >> choice;
if(choice == 3)
{
cout << "Be amazed at my psychic powers! For I am a computer!" << endl;
break;
}
if(choice == 2)
{
cout << "Hmm, ok. I was sure I had it. Let's try again!" << endl;
range_low = guess;
}
if(choice == 1)
{
cout << "Really? Ok, ok, one more try!" << endl;
range_high = guess;
}
} while(true);
return 0;
}
Here are two exercises for you to improve the above:
First, try to compare the logic of this code against the logic of your code and see where your code differs - try to understand why it was wrong. It will help to try to execute the program using pen and paper, just like you were a computer that understood C++.
Second, try to add code to ensure that the computer never guesses the same number twice.