Check if input is integer

前端 未结 2 1953
我在风中等你
我在风中等你 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: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(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.

提交回复
热议问题