c++ - 给定两个值时,输入循环循环两次
问题描述
所以我刚开始学习 c++ 并想做它,所以你必须输入一个 1-10 之间的数字,如果我运行程序就可以了。
#include <iostream>
#include <limits>
int main()
{
int a;
do
{
std::cout << "Enter a number between 1-10";
std::cin >> a;
if (std::cin.fail()) // if input is not an int cin fails
{
std::cin.clear(); // this clears the cin
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // this deletes the wrong character
std::cin >> a;
}
} while (a <1 || a >10);
std::cout << "Your number is " << a <<"";
}
问题是当您键入两个值时,例如15 15。它会打印两次。
Enter a number between 1-10Enter a number between 1-10
有没有办法删除空格,将两个值合并为一个数字,以避免这种行为?或者,还有更好的方法?
谢谢。
解决方案
为避免重复输入描述,您只需删除该if
语句,并将缓冲区清除和标志重置例程放在外部:
int main()
{
int a;
do
{
std::cout << "Enter a number between 1-10";
std::cin >> a;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while (a < 1 || a > 10);
std::cout << "Your number is " << a << "";
}
第一个值被解析,其余的都被清除。
当您输入非数字字符时,这具有避免无限循环的额外好处,而这些字符不是用 if 语句解决的。
推荐阅读
- sql - SQL Server:如何在按用户分组的日期范围内选择第一个和最后一个值
- sql-server - SQL 解决没有可重复读取或 TABLOCKX 的左连接问题
- python - Python - 在没有 Redis 库的情况下连接 Redis
- flutter - Flutter Drawer - 无法编辑颜色
- c# - 使用 Azure Key Vault 对机密(类别)进行排序
- c# - 当 SQL Server 中的数据类型为十进制 (7,6) 时,将数字转换为数据类型数字的算术溢出错误
- typescript - 当您将 A 类型的对象转换为 B 类型时,对象参数会发生什么 - Typescript
- tensorflow - 机器学习估计器训练步骤无法在终端中显示
- javascript - DOM 中是否有任何其他可用的位置或维度属性不在列表中?
- c++ - VSCode 包含路径错误,它不允许我包含父目录中的文件