Noob question - Loops

I have absolutely no programming experience, save the couple of days since i picked up "Jumping Into C++" by Alex Allain.

I am having some trouble with one of the practice assignments:

I have to write out a list, the user selects one from the list and if the choice does not match anything on the list then the list must be reprinted until a match is made.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  int main()
{

    string selection;

    while (selection != "Human" ||  "Dwarf" || "Elf" || "Orc" || "Troll")
    {

    cout << "Select an race: " << "\n";
    cout << "Human" << "\n";
    cout << "Dwarf" << "\n";
    cout << "Elf" << "\n";
    cout << "Orc" << "\n";
    cout << "Troll" << "\n";
    getline(cin, selection, '\n');
    cin.ignore();

    }

    cin.get();
    return 0;
}


The list is always repeated, even when a listed race is chosen. I have a strong feeling that the condition is not valid.

Any help would be appreciated
Your while condition is equivalent to:

while ( (selection != "Human") || ("Dwarf") || ("Elf") ... )

Since "Dwarf" and "Elf" and company evaluate to non-zero values in the context of a boolean condition they will always be true and the loop will always execute.

What you want is:

while( selection != "Human" && selection != "Dwarf" && selection != "Elf" ... )
Last edited on
Thanks cire. I am still trying to wrap my head around how boolean works, i will study it further and hopefully things will become clear.

Thanks again.
Topic archived. No new replies allowed.