Do-while endlessly looping cout, ignores cin

守給你的承諾、 提交于 2019-12-01 11:26:25
Johnsyweb

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.

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

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