Do-while endlessly looping cout, ignores cin

ε祈祈猫儿з 提交于 2019-12-01 09:28:00

问题


This program prints a specified amount of numbers within a specified range. However, when I enter a character, it just endlessly loops whichever do-while loop I do it in. E.g: If I enter a character in "Enter maximum number" cin, it just spams "Enter maximum number" endlessly, it just skips the cin and loops the cout (same goes for the other 2 do-whiles. Anyone know why?

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

int roll(int mini, int maxi)
{
        int v = maxi - mini;
        int x  = mini + (rand() % (v+1));
        return x;

}
void caller()
{
    int a;
    int b;
    int c;

    do {
    cout << "Enter minimum number" << endl;
    cin.clear();
    cin >> a;
    } while (cin.fail());

    do {
    cout << "Enter maximum number" << endl;
    cin.clear();
    cin >> b;
    } while (cin.fail() || a > b);

    do {
    cout << "How many rolls?" << endl;
    cin.clear();
    cin >> c;
    } while (cin.fail());

    for (int i = 0; i < c; i++)
    cout << roll(a, b) << endl;
}

int main()
{
    srand (time(NULL));
    caller();
    return 0;
}

回答1:


I prefer not to use istream::fail() for loop control. See Why is iostream::eof inside a loop condition considered wrong? for a similar issue.

Instead, I rely upon the return value of istream::operator >>.

I also use the following function to reset the flags and clear the input on input stream:

void flush_stream(std::istream& stream)
{
    stream.clear();
    stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

See How do I flush the cin buffer? for more on this.

So I'd code your input checks thus:

int get_valid_number(const std::string& prompt)
{
    int number = 0;

    bool valid = false;
    while (!valid)
    {
        std::cout << prompt << std::endl;
        if (std::cin >> number)
        {
            valid = true;
        }
        flush_stream(std::cin);
    }

    return number;
}

Hopefully the benefits of extracting this into a function are obvious. See it run.




回答2:


You could try doing something like

int a;
string trash;

do {
  cout << "Enter minimum number" << endl;
  cin >> a;

  if(cin.fail()){
    cin.clear();
    cin >> trash;
  }

} while (cin.fail());

This will remove any bad input from the cin stream by throwing it into the trash string.

This link may help you understand these cin functions a bit better.

http://web.eecs.utk.edu/~cs102/lectures/cinLecture.html



来源:https://stackoverflow.com/questions/14907978/do-while-endlessly-looping-cout-ignores-cin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!