c++ - std::cin 在 do-while 循环中不起作用

标签 c++ visual-studio c++11

我正在尝试创建一个简单的程序来读取范围限制,然后在这些范围之间创建一个随机数。我的程序中的一切都在运行,但是当我运行代码时,第一条消息打印给用户,然后我输入我的最大范围,按下回车键,光标移动到下一行,仍然要求输入。

我在我的代码中看不到是什么原因导致的,我很困惑。

到目前为止,这是我的代码:

#include<iostream>
#include<limits>

using std::cout;
using std::cin;
using std::endl;

int main(){

    int maxRange; //to store the maximum range of our random numbers

    do {
       cout << "Please enter a maximum range \n";
       //use clear funtion to clear the fail bit
       cin.clear();
       //use ignore function to avoid bad input
       cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } while(!(cin >> maxRange)); //continue loop if cin fails

    int minRange; //to store the minimum range of random numbers

    do {
       cout << "Please enter a minimum range \n";
       //use clear funtion to clear the fail bit
       cin.clear();
       //use ignore function to avoid bad input
       cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } while(!(cin >> minRange)); //continue loop if cin fails

    int randomNumber = rand() % maxRange + minRange;

    cout << "The random number that you have generated is: " << randomNumber << endl;

    return 0;
}

编辑: 问题是忽略功能。这是我的更正循环的工作代码:

if(!(cin)){
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   }

最佳答案

第一个 do..while() 循环中的 cin.ignore() 会在尝试读取循环条件中的值之前丢弃第一行输入。如果您两次输入最大范围,您的程序确实(有点)工作,因为它成功读取了第二行。也许删除第一个循环中的 cin.ignore() 行。

不过,您稍后在选择随机数时也有错误...

int randomNumber = rand() % maxRange + minRange;

应该是:

int randomNumber = rand() % (1 + maxRange - minRange) + minRange;

获取 minRangemaxRange 的范围。

关于c++ - std::cin 在 do-while 循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26454522/

相关文章:

c++ - 使用 qmake 执行 shell 命令

c++ - 网 bean 10 : error: linker command failed with exit code 1 (use -v to see invocation)

c++ - 将前向声明的类型转换为 void 是否合法?

c# - 有什么方法可以将类库函数转换成exe?

c++ - std::vector<char> 的自定义分配器被忽略

c++ - 有一个空捕获列表的 lambda 不能默认构造的原因吗?

c++ - 这段代码的递归形式是什么?

visual-studio - Visual Studio 2015 中的后期绑定(bind)错误

c# - Designer 在 InitializeComponent 中创建一些字段而不是创建全局变量

c++ - 以模板函数作为参数的可变参数模板函数