首页 > 解决方案 > 给定两个值时,输入循环循环两次

问题描述

所以我刚开始学习 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

有没有办法删除空格,将两个值合并为一个数字,以避免这种行为?或者,还有更好的方法?

谢谢。

标签: c++validationuser-inputcin

解决方案


为避免重复输入描述,您只需删除该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 语句解决的。


推荐阅读