jeudi 24 mars 2016

Does using "else if" eliminate the need for breaks after each condition in a while loop?

Does using "else if" eliminate the need for breaks after each condition in a while loop? I want to exit out of the loop when one of the correct inputs has been entered.

The first version of my code looked like this

string s;
string str;
while (true) {
        cin >> s;
        if (s == "a") {
             str = "Apple";
             break;
        }
        if (s == "b") {
             str = "Banana";
             break;
        }
        ... more ifs ...
        else {
            cout << "Did not recognize input." << endl;
            continue;
        }
        break;
    }

Can I change it to the code below without negative consequence? It's much shorter and nicer-looking to me.

string s;
string str;
while (true) {
        cin >> s;
        if (s == "a") str = "Apple";
        else if (s == "b") str = "Banana";
        else if (s == "c") str = "Cat";
        ... more else-ifs ...
        else {
            cout << "Did not recognize input." << endl;
            continue;
        }
        break;
    }

Aucun commentaire:

Enregistrer un commentaire