condition being met, wrong branch taken...

Hey Everyone,

I'm testing for a condition using a string data type. For a reason I can figure out, the first if statement is "always true." On line 8, I added statement to print the variable 'response', just to be sure.

Thanks in advance!



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    srand(static_cast<unsigned int>(time(0)));
        int guess = rand() % high + low;
        cout << "\nGuessing... " << guess << endl;
        while (guess != myNumber) {
            cout << "\nIs this guess higher or lower than your number? ";
            string response;
            cin >> response;
            cout << endl << endl << response << endl << endl;
            if (response == "higher" || "Higher" || "H" || "h"){
                cout << "\nOkay, guessing lower...";
                high = guess;
                guess = rand() % (high - low) + (low +1);
                cout << guess;
            }
            else if (response == "lower" || "Lower" || "L" || "l"){
                cout << "Okay, guessing higher...";
                low = guess;
                guess = rand() % (high - low) + (low + 1);
                cout << guess;
            }
             else
                cout << "Invalid Response";
        }
try this:

if (response == "higher" || response == "Higher" || response == "H" || response == "h"){

In general it is probably best not to try and cater for every combination of answer - just have them enter H or L. Use the toupper or tolower function to make your logic easier.

Hope all goes well.
Last edited on
Thanks IdeasMan, It worked like a charm.

I'm just starting to get back into programming and I have forgotten some of the rules.

And okay, I'll try to avoid catering to every possible logical response.

thx again
Topic archived. No new replies allowed.