gpt4 book ai didi

c++ - 给定两个值时,输入循环循环两次

转载 作者:行者123 更新时间:2023-12-03 06:53:53 25 4
gpt4 key购买 nike

所以我刚开始学习 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 语句未处理的非数字字符时,这具有避免无限循环的额外好处。

关于c++ - 给定两个值时,输入循环循环两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64508541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com