C++中使用while(cin)之后还要使用cin怎么清空之前的输入啊


int main()
{
    double x, y, z;
    cout << "enter two numbers" << endl;
    while (cin >> x >> y)
    {
        z = hmean(x, y);
        cout << "harmonic mean of " << x << " and " << y << " is " << z << endl;
        cout << "enter next set of numbers <q to quit> ;";
    }
    cin.clear();
    cin.get();//请问下为什么加上这两行才可以在输入q离开第一个循环之后可以继续输入啊
    cout << "Done." << endl;
    cout << "------------------" << endl;
    cout << "enter two other numbers" << endl;
    double x1, y1, z1;
    while (cin >> x1 >> y1)
    {
        if (hmean(x1, y1, &z1))
        {
            cout << "harmonic mean of .. " << x1 << " and " << y1 << " is " << z1 << endl;
        }
        else
        {
            cout << "one value should not be the negative" << " of the other - try again.\n";
        }
    }
    while (cin.get() != '\n')
    {
        continue;
    }
    cout << "Done." << endl;
    system("pause");
    return 0;
}
double hmean(double a, double b)
{
    if (a == -b)
    {
        cout << "untenable arguement to hmean()\n";
        abort();
    }
    return 2.0 * a * b / (a + b);
}
bool hmean(double a, double b, double* ans)
{
    if (a == -b)
    {
        *ans = DBL_MAX;
        return false;
    }
    else
    {
        *ans =  2.0 * a * b / (a + b);
        return true;  
    }
}

请问下为什么加上cin.clear()和cin.get()这两行之后才可以在输入q离开第一个循环之后可以继续输入啊

你退出的时候用cin >>  double 类却传入了 ‘q’ 字符,这会导致cin状态置错,这时使用:

```c

cin.clear();

```

可以消除错误状态,恢复继续标准输入状态。

而为了再次使用 cin >> double,必须清除缓存流中的其他数据,如'q',这时可以用

```c

cin.get(); // 去除 ‘q’,cin会跳过 '\n' 读取其他数据

```

如果结束cin用的是“quit”,单用一次cin.get()是不行的,需要如下的函数去除

```

cin.ignore(10, '\n');  //去除10个以内的字符,直到遇到 '\n'

```

简单来说就是不让你敲的回车影响输入。