Do-while endlessly looping cout, ignores cin

后端 未结 2 2052
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 01:21

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.

2条回答
  •  伪装坚强ぢ
    2021-01-15 01:56

    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::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.

提交回复
热议问题