Check if input is integer

前端 未结 2 1952
我在风中等你
我在风中等你 2021-01-22 17:09

In order to learn C++, I\'m translating a program I wrote in Python.

I wrote this

n = 0
while n < 2:
    try:
        n = int(raw_input(\'Please inser         


        
相关标签:
2条回答
  • 2021-01-22 17:30

    Your Python can code be translated more directly if you use C++11's std::stoi combined with std::getline to read a whole line of input. This is much easier than struggling with standard I/O error handling, which arguably does not have a very user-friendly interface.

    std::stoi throws std::invalid_argument if the input could not be correctly parsed as an integer number, and std::out_of_range if the number is too small or too big to fit in an int.

    #include <iostream>
    #include <string>
    
    int main() {
        int n = 0;
        while (n < 2) {
            std::cout << "Please insert an integer bigger than 1: ";
            std::string input;
            std::getline(std::cin, input);
            try {
                n = std::stoi(input);
            } catch (std::exception const&) {
                std::cerr << "ERROR!\n";
            }
        }
    }
    

    If you want to make the code even more similar to its Python equivalent, then you can encapsulate the input in a function:

    #include <iostream>
    #include <string>
    
    int raw_input(std::string const& message)
    {
        std::cout << message;
        std::string input;
        std::getline(std::cin, input);
        return std::stoi(input);
    }
    
    int main() {
        int n = 0;
        while (n < 2) {
            try {
                n = raw_input("Please insert an integer bigger than 1: ");
            } catch (std::exception const&) {
                std::cout << "ERROR!\n";
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-22 17:46

    For a situation like this, you'd probably want to read the input as a string, then inspect the string (e.g., "contains only digits, up to a maximum of N digits"). If and only if it passes inspection, parse an int out of it.

    It's also possible to combine the inspection and conversion--for example, Boost lexical_cast<int>(your_string) will attempt to parse an int out of the string, and throw an exception if it can't convert the whole thing to an int.

    0 讨论(0)
提交回复
热议问题