C++ How to protect against invalid input?

In my program, I want users to choose between two choices. Simply, 1 or 2. I have written the program to where it will protect against an invalid numeric value such as 3 or 28, but I cannot protect against alphabetical input.

Code is as follows:

int whileInt = 0;
int choiceOne_One = 0;
while(whileInt == 0)
{
    cin >> choiceOne_One;

    if(choiceOne_One != 1 && choiceOne_One != 2)
    {
        cout << "Woah! That wasn't an option! Try Again.n";
    }
    else if(choiceOne_One == 1)
    {
        whileInt++;
        cout << "nYou have died. Be more careful.n";
    }
    else if(choiceOne_One == 2)
    {
        whileInt++;
        cout << "nYou have survived the alien invasion due to your cunning sense of "
            "safety.nCongratulations.n";
    }
}

My brain still works in Java, please help me figure this out. It will definitely be appreciated.

Answer

Try reading a std::string with std::getline, then simply compare the string with “1” or “2”. Otherwise, you can just read the whole line with std::getline, then use std::stoi (C++11) to transform the read string into an integer. The result of std::stoi tells you whether the transformation was successful or not (i.e., whether the string represented an integer). If successful, then you can simply compare the integer with 1 or 2. If not successful, then an std::invalid_argument or std::out_of_range exception is thrown.

First case (with std::string comparison):

#include <iostream>

int main()
{
    std::string input;
    std::getline(std::cin, input);
    if (input != "1" && input != "2")
        std::cout << "Invalid input!";
}

Second case (using std::stoi):

#include <iostream>

int main()
{
    std::string input;
    std::getline(std::cin, input);
    int n = std::stoi(input); // throws exception if cannot convert to int
    if (n != 1 && n != 2)
        std::cout << "Invalid input!";
}