checking cin input, clearing input buffer

主宰稳场 提交于 2019-12-31 05:39:04

问题


New to c++ - trying to check for format of input. Have tried everything, at wit's end. Any help would be appreciated. I've broken down my problem to this basic case:

while(1) {
    cin >> x;
    cout << "asked!" << endl;
    cin.ignore(1000, 'n');
}

will result in infinite loop of "asked!" after the first invalid input (entering not int for x). I want to handle incorrect input. The following will not work:

do {
    cin.clear();
    cin >> x >> y;
    if (cin.fail()) 
    {
        cout << "Invalid input." << endl;
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

} while (cin.fail());

回答1:


You should use std::cin.clear() immediately before std::cin.ignore() to clear the stream's error state, otherwise all future cin operations will exit/fail. You can also test the success of std::cin operations more directly...

do {
    if (std::cin >> x >> y) break;
    std::cout << "Invalid input, please try again...\n";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while (true);



回答2:


the following worked:

 do {
    if (cin >> customers >> chairs)
        break;
    if (cin.fail())
    {
        cout << "Invalid input." << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

    }

} while (true);

thanks to Tony D



来源:https://stackoverflow.com/questions/28533483/checking-cin-input-clearing-input-buffer

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