0

My code is meant to be a number guessing game. The issue I'm having is that the else statement doesn't work the way I would intend it to account for non-integer input. The cout lines in the else statement still display even after the other if statement have run, making it more of an and statement than an if statement. Non-integer responses from the user cause the program to run indifinately. The code is the following (I'm new to this and had trouble getting stack overflow to actual display my code as code so sorry for the mess):

#include <iostream>
#include <math.h>

using namespace std;

int main(){
    //   this will generate a random number between 0 and 99
    int pick, attempt;
    pick = rand() % 100; //picking value from 0 to 99
    attempt = 200;
    do  {
        cout << "\nguess a number between zero and ninety enter code herenine\n";
        cin >> attempt;
        if (attempt > pick) {
            cout << "The number you have picked is too high.\n";
            cout << "Please guess again\n" << endl;
        }
        if (attempt < pick) {
            cout << "The number you have picked is too low.\n";
            cout << "Please guess again.\n" << endl;
            }
        if (cin.bad()) {
            cout << "Your input must be an integer\n" << endl;
            cin.clear();
            cin.ignore(1000,'\n');
        }
    }while (attempt != pick);
        cout << "Congratulations, " << attempt << "is right!\n";
    return 0;
}
  • You mention an else statement in your description, yet there are no else statements in the code you provided. – DeducibleSteak Feb 16 '20 at 02:32
  • Seems a bit unfair to prompt for a "number between zero and ninety" and then generate a number between 0 and 99. Anyways, there's not a single `else` statement in your code. Probably a clearing issue: https://stackoverflow.com/a/19521636/2711811. –  Feb 16 '20 at 02:32
  • Another link about dealing with invalid input on cin: https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input – DeducibleSteak Feb 16 '20 at 02:35
  • Sorry, the last if statement was an else statement with no condition. I forgot I changed it because I was trying to see if that would do anything and it didn't. And the source code I wrote actually say ninety nine! Like I said, I haven't used stack overflow. must have done something and gotten rid of it by accident. – trymefly Feb 16 '20 at 14:30
  • I was able to use one of your links, thanks. – trymefly Feb 16 '20 at 14:35

0 Answers0