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

Input cycle loops twice when given two values

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

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

谢谢。

为了避免重复输入描述你只需要删除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 语句未处理的非数字字符时,这具有避免无限循环的额外好处。