如何在C ++中检查cin是否为int? [英] How to check if cin is int in c++?

查看:108
本文介绍了如何在C ++中检查cin是否为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序此时仅接受int作为用户输入,如果不是,请继续询问用户,直到获得正确的整数为止.这是下面的代码:

I'm writing a program that only accepts int for user input at this point, if its not, keep asking user until get the right integer. Here is the code below:

cout << "enter two integers: " << endl;
string input1, input2;
cin >> input1;
cin >> input2;

while (//if they are not integers)
...//ask again

如您所见,我使用字符串存储输入,但是我不知道如何检查此字符串是否仅包含整数.

As you can see, I use string to store the input, but I don't know how to check this string contains only an integer number.

推荐答案

cin 如果用户输入的数据类型不正确,则会切换为 failbit .将输入的数据类型更改为 int 并检查此 failbit ,将使您可以验证用户输入.

cin will toggle it's failbit if the user does not enter a correct data type that it was expecting. Changing the datatype of the inputs to int and checking this failbit will allow you to validate user input.

#include <limits> // This is important!

cout << "enter two integers: " << endl;
int input1, input2;
std::cin >> input1;
std::cin >> input2;

while (!std::cin.good())
{
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    ...//ask again
}

这篇关于如何在C ++中检查cin是否为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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