cin.clear() 不工作 - 不读取输入

cin.clear() not working - does not read input

我有一个代码,我必须在其中读取整数,直到用户给出一个字符串 "q",然后显示并处理它们。我必须一遍又一遍地重复,直到用户需要为止。我们可以使用 cin.clear() 清除错误标志。问题是在尝试读取 int 失败后(用户给了 q)它不读取输入并为下一个输入提供一些任意输入。这是归结为必要内容的代码:

#include <iostream>
using namespace std;

int main(){

    // Declare the variables
    int x,y;

    // Read the wrong input - setting error flag
    cin >> x; // Give a string as input for eg. - "q" 
              // Without the quotes obviously 

    // Clear the error flag
    cin.clear();

    // Try to read again and display
    cin >> y; // Error!! Does not read input and
    cout << y << endl; // Displays 0

    return 0;
}

如果我添加更多变量,它会给出一些随机的东西,例如 4309712、-1241221 等。这里发生了什么?为什么 cin.clear() 不工作?

编译器属性

-------------- Build: Debug in Competition (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions -g -std=c++14  -c D:\CP\Competition\main.cpp -o obj\Debug\main.o
mingw32-g++.exe  -o bin\Debug\Competition.exe obj\Debug\main.o   
Output file is bin\Debug\Competition.exe with size 1.05 MB
Process terminated with status 0 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))

IDE 代码块 16.01

clear 的调用不会从流中删除错误的输入。 您应该在 clear 之后使用 ignore 来删除不需要的字符。 例如:

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

另请参阅references