C++正在检查整数
C++ Checking for an integer.
C++新手。处理错误时出现正确循环问题。我正在尝试检查用户输入是否是一个整数,并且是正的。
do{
cout << "Please enter an integer.";
cin >> n;
if (cin.good())
{
if (n < 0) {cout << "Negative.";}
else {cout << "Positive.";}
}
else
{
cout << "Not an integer.";
cin.clear();
cin.ignore();
}
}while (!cin.good() || n < 0);
cout << "ndone.";
当输入非整数时,循环中断。在这个循环中,我觉得我误解了cin.clear()
和cin.ignore()
的固有用法以及cin
的状态。如果我去掉cin.ignore()
,循环将变为无穷大。为什么会这样?我该怎么做才能把它变成一个功能优雅的循环呢?非常感谢。
在非整数分支中,您正在调用更多的cin
方法,因此cin.good()
将重置为true。
你可以把你的代码改成这样:
while(1) { // <<< loop "forever"
cout << "Please enter an integer.";
cin >> n;
if (cin.good())
{
if (n < 0) {cout << "Negative.";}
else { cout << "Positive."; break; }
} // ^^^^^ break out of loop only if valid +ve integer
else
{
cout << "Not an integer.";
cin.clear();
cin.ignore(INT_MAX, 'n'); // NB: preferred method for flushing cin
}
}
cout << "ndone.";
或者你可以像这样进一步简化它:
while (!(cin >> n) || n < 0) // <<< note use of "short circuit" logical operation here
{
cout << "Bad input - try again: ";
cin.clear();
cin.ignore(INT_MAX, 'n'); // NB: preferred method for flushing cin
}
cout << "ndone.";
int n;
while (!(cin >> n)||n<0)//as long as the number entered is not an int or negative, keep checking
{
cout << "Wrong input. Please, try again: ";
cin.clear();//clear input buffer
}
//only gets executed when you've broken out of the while loop, so n must be an int
cout << "Positive.";
cout << "ndone.";//finished!
应该做你想做的事。
相关文章:
- 检查输入是否不是整数或数字
- 检查TCHAR数组输入是否为带符号整数C++
- 检查字符串是否为整数
- 检查节点的输入验证的整数
- 如何检查是否定义了固定宽度的整数
- 优化正在杀死我在 clang 6 中的整数溢出检查
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- 将字符串转换为整数类型T,检查是否存在溢出
- 在C/C++中检查数字是否为整数(不带scanf/gets/etc)
- 如何在 c++ 中解析包含整数的字符串并检查是否大于最大值
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- QT按钮组和可检查的按钮:如何将切换信号与整数和布尔值连接?
- 如何检查商是否为整数?C++
- 检查Android NDK COD中的整数溢出
- 如何使用条件来检查类型名 T 是否是 C++ 中浮点类型的整数类型
- 我们如何找到 N sqrt(m) 并检查答案是否是 C++ 中的整数
- 检查整数是否增加了C++
- 检查用户输入的整数是否包含所有 1 或 0?
- 如果数字是整数,我如何检查此代码
- 如何检查整数是否包含数字 0 和 1