String casting failure in unsigned int

I have an annoying problem with the C ++ function that I wrote, and the purpose of which is to validate user input. The function reads user input, checks if it is a number and, if so, if it is in the range [min, max].

The problem occurs when I call a template function with an unsigned type, for example size_t, and the input is a negative number. The string stream converts the string to something like 4294967291. I can see that the program converts the data to a value close to the maximum value of the unsigned data type (defined in the numeric_limits header), but my question is, why ifshould I stop at sstream >> value?

My code is:

template <class T>
T getNumberInput(std::string prompt, T min, T max) {
    std::string input;
    T value;

    while (true) {
        try {
            std::cout << prompt;
            std::cin.clear();
            std::getline(std::cin, input);
            std::stringstream sstream(input);

            if (input.empty()) {
                throw EmptyInput<std::string>(input);
            } else if (sstream >> value && value >= min && value <= max) {
                std::cout << std::endl;
                return value;
            } else {
                throw InvalidInput<std::string>(input);
            }
        } catch (EmptyInput<std::string> & emptyInput) {
            std::cout << "O campo nΓ£o pode ser vazio!\n" << std::endl;
        } catch (InvalidInput<std::string> & invalidInput){
            std::cout << "Tipo de dados invΓ‘lido!\n" << std::endl;
        }
    }
}

Thank you for your time!

+1
2

++, unsigned n , 2 ^ n. , 0 2 ^ n-1 2 ^ n. C.

, .

, if >> && bad-code-meter. >> &&. , , , >> . ... , , .

, . , GUI ? , , ...

hth.,

+2

, . , try. , , . try if (input.empty())... try . . , . , . , .

, ,

+1

Source: https://habr.com/ru/post/1774256/


All Articles