问题描述
所以我刚开始学习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语句无法解决的非数字字符时,可以避免无限循环。