dimanche 23 septembre 2018

If/else in C++ to get a valid input? [duplicate]

This question already has an answer here:

I am trying to force a valid input from a given set of options using an if/else statement. The program seems to skip right over the if/else and continue on to the next field. Where am I going wrong here?

cout << "Please enter the atomic symbol for the metal you are interested in: ";
    getline(cin, userMetalChoice);
    if (userMetalChoice == "Cu" || "Al" || "Ag" || "Au" || "Pt")
    {
        cout << "\nAre we using a 2-door or 4-door Mini Cooper?"
            << "Please type 2 or 4: ";
        getline(cin, userMiniChoice);
    }
    else /*if (userMetalChoice != "Cu" || "Al" || "Ag" || "Au" || "Pt")*/
    {
        cout << "Please choose one of the listed metals.";
    }

What I was able to find work for me is this:

cout << "Please enter the atomic symbol for the metal you are interested in: ";
    getline(cin, userMetalChoice);
    if (userMetalChoice == "Cu" || userMetalChoice == "Al" || userMetalChoice == "Ag" || userMetalChoice ==  "Au" || userMetalChoice ==  "Pt")
    {
    }
    else
    {
        cout << "\nThat is not a valid option!\n";
        cout << "\nPlease enter the atomic symbol for the metal you are interested in: ";
        getline(cin, userMetalChoice);
    }

Is there any possible negative consequences for leaving the "if" part of the if/else statement within the curly brackets blank?

Aucun commentaire:

Enregistrer un commentaire