简体   繁体   中英

Accepting only numbers in the user input c++

Right now I am using this function to get the user input.

int getOnlyNumber(int num)
{
    while (!(cin >> num)) {
        // Reset the input:
        cin.clear();
        // Get rid of the bad input before return was pressed:
        while (cin.get() != '\n')
        {
            continue;
        }
        // Ask user to try again:
        cout << "Please enter a number:  ";
    }
    return num;
}

This seems to only catch bad input if the letter is entered first. If a number is entered first, the program accepts it. Ex. it will accept 1e but will catch e1. This is being used like this:

displayChoice = getOnlyNumber(displayChoice);

Where displayChoice is an int. What do i need to change to catch 1e as a input or any other input that starts with a number but has strings?

If you give it a partial number then, by default, it does the best it can and gives you the bits it did manage to understand.

If you want to see if there was an error during the conversion then you have to check cin.fail().

    while (!(cin >> num) || cin.get()!='\n') {
    ...

You can use std::all_of to test if an entire string is a number:

std::string str;
auto is_digit_check = [] (unsigned char c) { return std::isdigit(c); };
while (!(std::cin >> str) ||
       !std::all_of(str.begin(), str.end(), is_digit_check))
{
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

return std::stoi(str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM