DHowell
DHowell

Reputation: 17

why wont this do while loop exit after accepting input

Pretty straight forward. i dont understand why it wont quit the loop after not accepting a y char.

ive tried different variations of == and != with regards to y char and n char

vector<int> v;
    char ans;
    do
    {
        cout << "Enter scores, enter number outside of 0-100 to stop:\n";
        get_scores(v);
        print_stats(v);
        cout << "Do you want to try another set of scores? Y/N: \n";
        cin >> ans;
    } while (ans != ('n' || 'N'));

after typing any char, the loop keeps asking for more input. NOTE: the get scores and print stats functions work as their supposed to.

Upvotes: 0

Views: 63

Answers (3)

Turtlefight
Turtlefight

Reputation: 10800

Your comparison in the while condition is not correct, you probably meant to do

while (ans != 'n' && ans != 'N');

('n' || 'N') will be coerced to true (1), so you would check for a char of value 1 instead of 'n' / 'N'

Upvotes: 4

Jesper Juhl
Jesper Juhl

Reputation: 31459

while (ans != ('n' || 'N')) is the same as writing while (ans != (true)). You probably wanted while ((ans != 'n') && (ans != 'N')).

Upvotes: 0

alexrider
alexrider

Reputation: 4463

    } while (ans != ('n' || 'N'));

Here you are comparing char with boolean result of || operation for the 2 other chars. Which alway evaluates as true. So your while statement is effecitvely

    } while (ans != true);

to fix this you need to compare ans to both of the n and N and exit if one of them becomes true, for example:

    } while ((ans != 'n') && (ans != 'N'));

Upvotes: 2

Related Questions