如何在 C++ 中验证数字输入 [英] How to validate numeric input in C++
本文介绍了如何在 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屋!
查看全文