Check if input is integer

前端 未结 2 1951
我在风中等你
我在风中等你 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 
    #include 
    
    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 
    #include 
    
    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";
            }
        }
    }
    

提交回复
热议问题