If else statement not running C++ - c++

I am trying to make a simple guess the number game and when the answer is bigger than the number the if else statement does not trigger.
For example if the number is 20 and I choose something above 30 say 41 it will just end the code.
#include <iostream>
#include <string>
#include <cmath>
#include <unistd.h>
#include <chrono>
#include <thread>
#include <fstream>
#include <random>
#include <time.h>
#include "functions.h"
using namespace std;
void game() {
int number;
int answer;
cout << "Welcome to the guess the number game!" << endl;
cout << "The computer will generate a random number from 1 to 100 and you will try to guess it."<< endl;
cont();
ran(number,100,1);
START:
cout << number;
system("clear");
cout << "Type your answer here: ";
if (!(cin >> answer)) {
cin.clear();
cin.ignore(10000,'\n');
cout << "THAT IS NOT AN OPTION!" << endl;
sleepcp(250);
system("clear");
goto START;
}
int warmer1;
int warmer2;
warmer1 = number + 11;
warmer2 = number - 11;
if (answer > warmer2) {
if (answer == number) {
cout << "You got it!";
} else if (answer < warmer1) {
cout << "You are close."<< endl;
sleepcp(250);
system("clear");
goto START;
}
} else if (answer > number) {
cout << "Less." << endl;
sleepcp(250);
system("clear");
goto START;
} else if (answer < number) {
cout << "More."<< endl;
sleepcp(250);
system("clear");
goto START;
}
}
int main() {
game();
return 0;
}
Can anybody help with this thanks!!!

Consider this if statement when number is equal to 20 and answer is equal to 41.
if (answer > warmer2) {
if (answer == number) {
cout << "You got it!";
} else if (answer < warmer1) {
cout << "You are close."<< endl;
sleepcp(250);
system("clear");
goto START;
}
} else if (answer > number) {
In this case the if statement gets the control because answer is greater than warmer2. But answer is not equal to number (the first inner if statement) and answer is not less than warmer1.
In this case nothing occurs and the control is passed to the end of the program.
That is if this if statement
if (answer > warmer2) {
gets the control then the following if statements like for example this
} else if (answer > number) {
will be skipped.
In other words, what you do is what you get.
You could resolve your problem if instead of goto statements you used for example a while or do-while loop.

If you were to step through your code with a debugger (or at least print out some diagnostic messages describing your game's decisions), you would see exactly why the program is terminating.
Assuming number is 20 and answer is 41, then warmer1 is 31 and warmer2 is 9, thus:
void game() {
...
START:
...
if (answer > warmer2) { // 41 > 9 is TRUE
if (answer == number) { // 41 == 20 is FALSE
...
} else if (answer < warmer1) { // 41 < 31 is FALSE
...
goto START; // <-- NOT REACHED!
}
// <-- execution reaches here!
} else if (answer > number) { // <-- NOT EVALUATED!
...
goto START; // <-- NOT REACHED!
} else if (answer < number) { // <-- NOT EVALUATED!
...
goto START; // <-- NOT REACHED!
}
// <-- execution reaches here!
}
Since the game() function does not reach a goto START; statement, the loop ends and game() exits, and thus main() exits, terminating the program.
There is almost never a good reason to use goto in modern C++ coding. Use a while or do..while loop instead, eg:
#include <iostream>
#include <limits>
#include "functions.h"
using namespace std;
void game() {
int number, answer, warmer1, warmer2;
cout << "Welcome to the guess the number game!" << endl;
cout << "The computer will generate a random number from 1 to 100 and you will try to guess it." << endl;
cont();
ran(number, 100, 1);
warmer1 = number + 11;
warmer2 = number - 11;
do {
system("clear");
cout << "Type your answer here: ";
if (!(cin >> answer)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "THAT IS NOT AN OPTION!" << endl;
}
else if (answer == number) {
cout << "You got it!";
break;
}
else {
if (answer <= warmer1 && answer >= warmer2) {
cout << "You are close." << endl;
}
if (answer > number) {
cout << "Less." << endl;
}
else {
cout << "More."<< endl;
}
}
sleepcp(250);
}
while (true);
}
int main() {
game();
return 0;
}

Related

Do-while loop displays 2 prompt at a time, please reply [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
I'm new to programming and trying a program that You need to guess the name of a video game character, there are only 3 guesses if you ran out of guesses you will lose. I used a do-while loop here so I can do it again and again... The problem here is that every time The loop starts again It displays the prompt 2 times even though It's supposed to be 1 time prompt per guess but it displays 2 prompt. Can you please help me maybe I'm doing the algorithm wrong, Thanks!
#include <iostream>
using namespace std;
int main()
{
char rerun_option;
do {
string secretWord = "Arthur Morgan";
string guess;
int guessCount = 0;
int guessLimit = 3;
bool outofGuesses = false;
while (secretWord != guess && !outofGuesses) {
if (guessCount < guessLimit) {
cout << "Enter video game character name guess: ";
getline(cin, guess);
guessCount++;
}
else {
outofGuesses = true;
}
}
if (outofGuesses) {
cout << "You Lose!" << endl;
outofGuesses = false;
}
else {
cout << "You Win!" << endl;
}
cout << "Try Again?(Y/N) ";
cin >> rerun_option;
} while (rerun_option == 'Y' || rerun_option == 'y');
return 0;
}
EDIT: stackoverflow.com/a/21567292/4645334 is a good example of your problem, explains why you are experiencing it, and explains how you can solve it. I have provided a working example of your code below, as well as a link to more information on the use and description of cin.ignore().
#include <iostream>
using namespace std;
int main()
{
char rerun_option;
do {
string secretWord = "Arthur Morgan";
string guess;
int guessCount = 0;
int guessLimit = 3;
bool outofGuesses = false;
while (secretWord != guess && !outofGuesses) {
if (guessCount < guessLimit) {
cout << "Enter video game character name guess: ";
cin.ignore(); // <-- ADD THIS LINE RIGHT HERE
getline(cin, guess);
guessCount++;
}
else {
outofGuesses = true;
}
}
if (outofGuesses) {
cout << "You Lose!" << endl;
outofGuesses = false;
}
else {
cout << "You Win!" << endl;
}
cout << "Try Again?(Y/N) ";
cin >> rerun_option;
} while (rerun_option == 'Y' || rerun_option == 'y');
return 0;
}
https://www.tutorialspoint.com/what-is-the-use-of-cin-ignore-in-cplusplus

Play again option in C++ not working for number guessing game

When the user inputs 'Y' to try again, the game runs but only gives the user 1 try instead of 3 tries. Program works fine the first time it runs with 3 tries. I'm guessing something is wrong with my loop that it does not reset the number of tries? Let me know if there's any other way I could write my code to make it cleaner/better. Thanks a bunch.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int guessNum;
int randomNum;
int Tries = 0;
int startGame()
{
cout << "Number: ";
cin >> guessNum;
return guessNum, Tries;
}
int main(int a, int b)
{
while (true) {
a = guessNum;
b = Tries;
char ans;
// Random number
srand(time(NULL));
randomNum = rand() % 20 + 1;
// Introduction
cout << "Guess a number between 1 to 20. You have three attempts." << endl;
do
{
startGame();
if (guessNum < randomNum)
{
cout << "Wrong! It is too low." << endl;
}
else if (guessNum > randomNum)
{
cout << "Wrong! It is too high." << endl;
}
Tries++;
}
while (guessNum != randomNum && Tries < 3);
if (guessNum != randomNum) // Wrong answer & run out of tries
{
cout << "Oops.. All attempts used. The answer is " << randomNum << endl;
}
else if (guessNum == randomNum) // User guessed correct number
{
cout << "Yes! You are correct!" << endl;
}
cout << "Try again?";
cin >> ans;
cin.ignore();
if (ans == 'N')
{
cout << "Thanks for playing!";
break;
}
}
}
EDITED V1
#include <iostream>
#include <ctime>
using namespace std;
int guessNum;
int startGame()
{
cout << "Number: ";
cin >> guessNum;
return guessNum;
}
int main()
{
while (true) {
int randomNum;
int Tries = 0;
char ans;
// Random number
srand(time(NULL));
randomNum = rand() % 20 + 1;
// Introduction
cout << endl << "Guess a number between 1 to 20. You have three attempts." << endl;
do
{
startGame();
if (guessNum < randomNum)
{
cout << "Wrong! It is too low." << endl;
}
else if (guessNum > randomNum)
{
cout << "Wrong! It is too high." << endl;
}
Tries++;
}
while (guessNum != randomNum && Tries < 3);
if (guessNum != randomNum) // Wrong answer & run out of tries
{
cout << "Oops.. All attempts used. The answer is " << randomNum << endl;
}
else if (guessNum == randomNum) // User guessed correct number
{
cout << "Yes! You are correct!" << endl;
}
cout << "Try again? Y/N: ";
cin >> ans;
cin.ignore();
ans = toupper(ans);
if (ans == 'N')
{
cout << endl << "Thanks for playing!";
break;
}
else
{
Tries = 0;
}
}
}
Actually, your program has several defects.
Firstly, If you wonder why the game behaves unexpected way after the first one, You did not set back the Tries to 0 after playing the game.
And, int startgame() should return only one variable. You are trying to return guessnum and Tries at the same time. The only reason the first game is running as expected is that you are using global variables, which is also considered as a bad practice(Some company may fire you if you use it without any good reason).
Furthermore, you are getting two int function arguments from main call, which is not valid. (main function signature should be int main(void) or int main(int argc, char* argv[])). I am surprised that the compiler did not catch this error.
And the variables (int a, int b) are actually not used. When you find unused variables, it is usually a good practice to remove them for maintainability.
So int Tries = 0; is a global variable. It's set before main().
You basically have
int Tries = 0;
main()
{
while (true) {
do
{
Tries++;
} while(Tries < 3);
}
}
Do you see that for each iteration in while, the value of Tries from the previous iteration is used? You would need to reset it before iterating again.
But there is no reason to have "Tries" as a global variable since you only need to know about it in the while(true)-loop. This is generally the case for a variable - put it to the closest scope possible:
main()
{
while (true) {
int Tries = 0;
do
{
Tries++;
} while(Tries < 3);
}
}
Now it's correctly reset between loops, and it is clear it is only needed for the loop logic.
Try to do the same for you other variables.
Try:
if (ans == 'N')
{
cout << "Thanks for playing!";
break;
}
else
{
Tries = 0;
}

expected unqualified id before return 0

I'm new to C++. I have errors. But, i dont know how to fix it. Could anyone please help me? Thank you.
P - Print numbers
A - Add a number
M - Display mean of the numbers
S - Display the smallest number
L - Display the largest number
Q - Quit
Errors : expected unqualified id before return 0
error : expected ';' before {}
#include <iostream>
#include <vector>
using namespace std;
int main(){
char input {};
vector <double> numbers {};
int number{};
int sum{};
int min_number{};
int max_number{};
bool condition {true};
cout << "Enter a command" << endl;
cin >> input;
if(numbers.size() > 0){
while(condition){
if (input == 'P' || input == 'p'){
for(auto x: numbers)
cout << x << endl;
}
else if(input == 'A' || input == 'a'){
cout << "Enter a number";
cin >> number;
numbers.push_back(number);
}
else if(input == 'M' || input == 'm'){
for(auto x : numbers)
sum += x;
cout << sum / numbers.size() << endl;
}
else if(input =='S' || input == 's'){
for(size_t i {0}; i < numbers.size(); ++i)
if(numbers.at(i) < min_number)
min_number =numbers.at(i);
}
else if(input =='L' || input == 'l'){
for(size_t i {0}; i < numbers.size(); ++i)
if(numbers.at(i) > max_number)
max_number =numbers.at(i);
}
else if(input =='Q' || input == 'q'){
condition {false};
}
}
cout << "[] - list is empty, unable to calculate" << endl;
}
return 0;
}
In your section dealing with Q/q, the statement:
condition {false};
is not a valid form of assignment, you should instead use:
condition = false;
The braces are fine for initialisation, but that's not what you're trying to do on that line.
As an aside, this line:
if(numbers.size() > 0){
seems a little strange. Since you initialise the list to empty, the main loop will never start (because it's inside the if block) even though you have already asked the user for input.
That's a runtime error rather than a syntax error but you'll still need to fix it at some point.
I suspect that particular should should be done only as part of the calculation of the mean, so as to avoid dividing by zero.
I have written this for you. Since, you're a learner, I think that you should be practicing better things like STL functions and not using using namespace std; at top.
You may find some things new, but don't be frightened, just search them on some website like cppreference and see what that entity do and how to effectively use it.
There were many logical errors. #paxdiablo has mentioned them in his answer. I have removed every of them and this code works.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <vector>
int main() {
std::vector<double> numbers;
while (true) {
char input;
std::cout << "Enter a command: ";
std::cin >> input;
switch (std::toupper(input)) {
case 'P':
if (numbers.empty())
std::cerr << "The list is empty!" << std::endl;
else {
for (auto &&i : numbers)
std::cout << i << ' ';
std::cout << std::endl;
}
break;
case 'A': {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
numbers.push_back(number);
break;
}
case 'M':
if (numbers.empty())
std::cerr << "The list is empty! Cannot perform the operation!!";
else {
int sum = 0;
for (auto &&i : numbers)
sum += i;
std::cout << "Mean: " << (sum / numbers.size()) << std::endl;
}
break;
case 'S':
std::cout << "Smallest Number: " << *std::min_element(numbers.begin(), numbers.end()) << std::endl;
break;
case 'L':
std::cout << "Largest Number: " << *std::max_element(numbers.begin(), numbers.end()) << std::endl;
break;
case 'Q':
return 0;
default:
std::cerr << "Unrecognised Command!!" << std::endl;
}
}
return 0;
}

How to prompt user to re-loop the whole program?

I want the user to choose between playing the game again or ending the program, however when prompted, if they press 'y' the same thing gets repeated over and over instead of the whole program from the very beginning. I've tried while loops, do/while loops, if statements, rearranging the code, but nothing has worked. Any advice?
#include <iostream>
#include <string>
using namespace std;
int main(){
string animal = "fish";
string guess;
char choose = 'Y' ;
int count = 0;//keeps a running total of how many times the user
has guessed an answer.
int limit = 5;//allows user to guess only 5 times, otherwise
they loose the game.
bool out_of_guesses = false;//to check whether the user has run
out of guesses.
cout << "I am thinking of an animal.\n" << endl;
do{
while(animal != guess && !out_of_guesses){//Nested while
loop inside main loop to keep track of how many tries the user has
attempted and to validate their answers.
if(count < limit){
cout << "Can you guess what animal I am thinking of?: ";
getline(cin, guess);
count++;
if(animal != guess){
cout << "\nHmm, nope. That's not the animal I'm
thinking of." << endl;
if(count > 2 && count <5){
cout << "I'll give you a hint. It lives in
water." << endl;
}
}
}
else{
out_of_guesses = true;
}
}//End nested while loop
if(out_of_guesses){
cout << "\nI'm sorry, but you are out of guesses." <<
endl;
}
else{
cout << "\n*** Good job! You guessed the correct animal!
***" << endl;
cout << "\t\t><)))º> ❤ <º)))><\t\t" << endl;
}
//The do-while loop is there to ask the user if they wish to
play the game again.
cout << "Would you like to try again?(y/n): ";
cin >> choose;
if(choose == 'N' || choose == 'n')
break;
}while(choose == 'Y' || choose == 'y');
return 0;
}
The bool out_of_guesses = false; must be in-between while(true) and while(animal != guess && !out_of_guesses), and not outside the first while loop. Because our while loop condition is always false, and then it does enter it.
You should also reset your guess variable in-between those 2 loops, else same thing could happen (false while loop) in case of the answer is found.
Here the code with some refactoring/review, which I used the guess as upper case to handle any typography of the answer. I also removed the out of guess variable to use the count and limit one instead.
#include <iostream>
#include <string>
#include <cctype>
int main()
{
const std::string animal = "FISH";
const int limit = 5;
do
{
std::cout << "I am thinking of an animal.\n";
int count = 0;
std::string guess;
while(animal.compare(std::toupper(guess)) != 0 && count < limit)
{
std::cout << "Can you guess what animal I am thinking of?: \n";
std::cin >> guess;
count++;
if(animal.compare(std::toupper(guess)) != 0)
{
std::cout << "\nHmm, nope. That's not the animal I'm thinking of.\n";
if(count > 2)
{
std::cout << "I'll give you a hint. It lives in water.\n";
}
}
}
}//End nested while loop
if(count >= limit)
{
std::cout << "\nI'm sorry, but you are out of guesses.\n";
}
else
{
std::cout << "\n*** Good job! You guessed the correct animal! ***\n";
std::cout << "\t\t><)))º> ❤ <º)))><\t\t\n";
}
char choose = 'Y' ;
std::cout << "Would you like to try again?(y/n): ";
std::cin >> choose;
if(std::toupper(choose) == 'N') break;
} while(true);
return 0;
}

Error handling with c++

I need to do some error handling in c++ that corrects user input if it's a letter or a string. I need to use .at(), .length(), and atoi to handle this. I'm not sure how/where to implement those is the problem.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <time.h>
using namespace std;
int main() {
srand(time(0));
int number;
number = rand() % 50 + 1;
int guess;
int x;
for (x = 5; x > 0; x--) {
cout << "Guess my number, it's between 0-50. You have 5 guesses: ";
cin >> guess;
if (guess < number){
cout << "Your guess was too low" << endl;
}
else if (guess > number){
cout << "You guess was too high" << endl;
}
else {
cout << "You're exactly right!" << endl;
break;
}
} while (guess != number){
break;
}
return 0;
}
The best approach to input validation is to write a function that reads into a std::string, checks whatever is needed, and only returns a value when it passes the tests:
int get_value() {
std::string input;
int value = -1;
while (value < 0) {
std::cout << "Gimme a value: ";
std::getline(std::cin, input);
try {
value = std::stoi(input);
} catch(...) {
value = -1;
}
}
return value;
}