如何检查输入是否是C ++中的数字 [英] How to check if input is numeric in C++

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

问题描述

我想创建一个程序,该程序从用户接收整数输入,然后在用户根本没有输入任何东西时终止(即,只需按Enter键)。但是,我无法验证输入(确保用户输入整数,而不是字符串),atoi()将不起作用,因为整数输入可以多个数字。

I want to create a program that takes in integer input from the user and then terminates when the user doesn't enter anything at all (ie, just presses enter). However, I'm having trouble validating the input (making sure that the user is inputting integers, not strings. atoi() won't work, since the integer inputs can be more than one digit.

验证这个输入的最好方法是什么?我尝试过类似下面的方法,但我不知道如何完成它:

What is the best way of validating this input? I tried something like the following, but I'm not sure how to complete it:

char input

while( cin>>input != '\n')
{
     //some way to check if input is a valid number
     while(!inputIsNumeric)
     {
         cin>>input;
     }
}


推荐答案

cin 获取输入时, ,它会设置 failbit

When cin gets input it can't use, it sets failbit:

int n;
cin >> n;
if(!cin) // or if(cin.fail())
{
    // user didn't input a number
    cin.clear(); // reset failbit
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
    // next, request user reinput
}

当设置 cin failbit 时,使用 cin.clear() 重置流的状态,然后 cin.ignore() 清除剩余的输入,然后请求用户重新输入。只要设置了故障状态并且流包含错误的输入,流就会出现故障。

When cin's failbit is set, use cin.clear() to reset the state of the stream, then cin.ignore() to expunge the remaining input, and then request that the user re-input. The stream will misbehave so long as the failure state is set and the stream contains bad input.

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

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