-1

I found this similar question being asked so many times but I still couldn't find a solution for mine.

In my case, I want to display something when the user enters a number from 1 - 5, give an error when he inputs something wrong like characters, "3g", "3.", "b3" and any float number.

I tried the code below, but it created so many other problems. Like if I enter 3g or 3.5, it'll only take the 3 and ignore the rest so the (!cin) doesn't work at all.

Second, if I input something like a character, the __userChoice will be automatically converted into 0 and the program prints out "Please select a number from 1 to 5." instead of "Invalid input, please input an integer number.\n", which is what I want.

cout << "Please select: ";
cin >> __userChoice;
if (__userChoice > 0 && __userChoice < 5) {
    cout << "You select menu item " << __userChoice <<". Processing... Done!\n";
}
else if (__userChoice == 5) {
    Finalization(); //call exit
}
else if (__userChoice <= 0 || __userChoice > 5) {
    cout << "Please select a number from 1 to 5.\n";
}
else (!cin) {
    cout << "Invalid input, please input an integer number.\n";
}
cin.clear();
cin.ignore(10000, '\n');
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

0

operator>> is not guaranteed to output a meaningful integer value if a failure occurs, but you are not checking for failure before evaluating __userChoice, and the way your ifs are structured the else (!cin) check will never be reached. But even if operator>> is successful, you are not checking if the user entered more than just an integer.

To do what you are asking for, you should read from std::cin into a std::string first using std::getline(), and then use std::istringstream or std:stoi() (or equivilent) to convert the string to an int with error checking.

For example:

bool strToInt(const std::string &s, int &value)
{
    std::istringstream iss(s);
    return (iss >> value) && iss.eof();

    // Or:

    std::size_t pos;
    try {
        value = std::stoi(input, &pos);
    }
    catch (const std::exception &) {
        return false;
    }
    return (pos == input.size());
}

...

std::string input;
int userChoice;

std::cout << "Please select: ";
std::getline(std::cin, input);

if (strToInt(input, userChoice))
{
    if (userChoice > 0 && userChoice < 5)
    {
        std::cout << "You selected menu item " << userChoice <<". Processing... Done!\n";
    }
    else if (userChoice == 5)
    {
        Finalization(); //call exit
    }
    else
    {
        std::cout << "Please select a number from 1 to 5.\n";
    }
}
else
{
    std::cout << "Invalid input, please input an integer number.\n";
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770