如何验证数字输入C ++ [英] How to validate numeric input C++

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

问题描述

我想知道如何使用 std :: cin 将输入值限制为带符号的小数。

I'd like to know how to limit an input value to signed decimals using std::cin.

推荐答案

double i;

//Reading the value
cin >> i;

//Numeric input validation
if(!cin.eof())
{
    peeked = cin.peek();
    if(peeked == 10 && cin.good())
    {
             //Good!
             count << "i is a decimal";
        }
        else
        {
             count << "i is not a decimal";
         cin.clear();
         cin >> discard;
        }
}

这也会给出一个错误消息,输入-1a2 .0避免只分配-1给i。

This also gives an error message with the input -1a2.0 avoiding the assignation of just -1 to i.

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

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