检查输入是否为整数 [英] Check if input is integer

查看:128
本文介绍了检查输入是否为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了学习C ++,我正在翻译用Python编写的程序。

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

我编写了此

n = 0
while n < 2:
    try:
        n = int(raw_input('Please insert an integer bigger than 1: '))
    except ValueError:
        print 'ERROR!'

以便从用户那里获得大于1的整数。

in order to get an integer bigger than 1 from the user.

这是我目前用C ++编写的内容:

This is what I wrote in C++ for the moment:

int n = 0;
while (n < 2) {
    cout << "Please insert an integer bigger than 1: ";
    cin >> n;
}

我看了一下try-catch,看起来很简单。我关心的是如何检查输入是否为整数。我读了有关cin.fail()的文章,但找不到任何正式文档,也没有真正了解它的工作原理。

I took a look at try-catch and it seems pretty straight forward. My concern is about how to check the input is an integer. I read about cin.fail() but I couldn't find any official document and I didn't really get how it works.

所以,如何检查是否输入的是整数吗?

So, how can I check if the input is integer?

更多一般而言,如何检查输入的内容是否为 任何东西

More in general, how can I check if the input is "anything"?

推荐答案

在这种情况下,您可能希望将输入作为字符串读取,然后检查字符串(例如,仅包含数字,向上最多N个数字)。当且仅当它通过检查时,才从其中解析出 int

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.

也可以将检查合并和转换-例如,Boost lexical_cast< int>(your_string)会尝试从字符串中解析出一个int,如果无法转换为int,则会抛出异常。整个事情变成一个整数。

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.

这篇关于检查输入是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆