-1

I'm writing the classic "Guess my number" program.

I don't seem to understand why the while loop doesn't stop working even after I wrote "Success" and goes to the default route.

int xRan;

void rdm(int to, int from){
    srand(time(NULL));
    xRan = rand()%to+from;
}

void iGuess(){
    string b;
    int tries = 1;

    cout <<  "Think of a number between 1 and 100" << endl;
    rdm(100, 1);

    while(b != "Success" || b != "success"){

        cout << "is your number higher or lower than  " << xRan << ". (attempt #" << tries << ")" <<  endl;
        cout << "If I guessed your number, please type 'Success' " << endl;
        cout << "-->";
        cin >> b;

        if(b == "Lower" || b == "lower"){
            rdm(xRan, 1);
            tries++;

        }else if(b == "Higher" || b == "higher"){
            rdm(100, xRan);
            tries++;

        }else{

        cout << "This is not a valid choice." << endl;

        }

    }
    cout << "I'm so good! I did it in " << tries << "attempts!" << endl;
}
Zeptile
  • 23
  • 1
  • 3
  • Zeptile, I've removed second question "Second, I'd like to have some advices on writing a better AI to find the number." from your post as it generally not a good idea to ask 2 questions in one. Feel free to revert my changes and improve your question yourself. You can ask second question as new one, but please make sure to search for similar posts as you may not be the only person writing such game. – Alexei Levenkov Dec 10 '14 at 07:24

1 Answers1

4

You never leave your for loop because you are checking if it is "Success" or "success". Either one can be true and go into the loop. So whether you type it with capitals or not one of those will be true. Instead write

while(b != "Success" && b != "success")
marsh
  • 2,592
  • 5
  • 29
  • 53
  • While this suggestion fixes immediate problem and hence proper answer, please don't use it in your code to do case insensitive comparison and instead follow suggestions in http://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c – Alexei Levenkov Dec 10 '14 at 07:20