检查cin输入,清除输入缓冲区

检查cin输入,清除输入缓冲区

问题描述:

新增到c ++ - 尝试检查输入的格式。已经尝试了一切,在机智的尽头。任何帮助将不胜感激。我已经把我的问题分解到这个基本情况:

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');
}

会导致无限循环的问!后的第一个无效的输入(输入not int为x)。我想处理不正确的输入。以下不工作:

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());


您应该使用 std: :cin.clear()紧接在 std :: cin.ignore()之前清除流的错误状态,否则所有未来 cin 操作将退出/失败。您还可以更直接地测试 std :: cin 操作的成功...

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);