mardi 24 octobre 2017

Efficient way for a while loop with string for entire alphabet (C++)

I'm very new to c++ and am working on getting the hang of functions. For this assignment, I'm programming a calculator.

My question revolves around this snip bit of code:

  else
    {
        cout << "\nEnter a letter from the selection!";
    } 

If I do this and enter just any letter, the code will continue to the next function and ask the user to enter a number. Well, I figured a while loop would fix this, but I can't figure out any other way to do it besides listing the entire alphabet in my bool statement! Is there a more efficient way to do this? Here is my entire function for reference:

string mathCalcChoice(string letter)
{
    string name;

    if ((letter == "A") || (letter == "a"))
    {
        name = "add";
    }

    else if ((letter == "B") || (letter == "b"))
    {
        name = "subtract";
    }

    else if ((letter == "C") || (letter == "c"))
    {
        name = "divide";
    }

    else if ((letter == "D") || (letter == "d"))
    {
        name = "multiply";
    }

    else if ((letter == "E") || (letter == "e"))
    {
        name = "the power of";
    }

    else
    {
        cout << "\nEnter a letter from the selection!";
    } 

    return name;
}

Aucun commentaire:

Enregistrer un commentaire