Search code examples
c++if-statementgoto

If else statement not running 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!!!


Solution

  • 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.