std::cin infinite loop from invalid input [duplicate]

余生长醉 提交于 2019-12-02 05:01:44

问题


Please read the following code:

#include <iostream>
#include <cstdlib>
int main() {
    std::cout << "Please input one integer." << std::endl;
    int i;
    while (true) {
        std::cin >> i;
        if (std::cin) {
            std::cout << "i = " << i << std::endl;
            break;
        } else {
            std::cout << "Error. Please try again."<< std::endl;
            std::cin.ignore();
            std::cin.clear();
        }
    }
    std::cout << "Thank you very much." << std::endl;
    std::system("pause");
    return 0;
}

When I give std::cin an invalid input, such as w, then Error. Please try again. is outputed infinitely. I thought std::cin.ignore would blank the input stream, and std::cin.clear would resume it to normal state. So why does the infinite loop happen?


回答1:


By default, std::basic_istream::ignore() ignores only 1 character:

basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() );

(From http://en.cppreference.com/w/cpp/io/basic_istream/ignore)

More idiomatic use for your case seems to be the one from the example there:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Also, note that you want to call clear() before the ignore() call, so the input extraction of ignore() will succeed instead of returning immediately.



来源:https://stackoverflow.com/questions/38890379/stdcin-infinite-loop-from-invalid-input

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