本文介绍了有关cin.clear()的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在阅读《加速的C ++》一书.(如果你们有书,我的问题在第57页上)

I am just working through the book Accelerated C++. (My problem is located on page 57, if you guys have the book with you)

问题如下:我们确实具有读取学生成绩的功能:

The problem is the following:We do have a function which reads student grades:

...
while (in >> x) {    // in and x are defined as an istream& and as a double
    hw.push_back(x);    // hw is vector defined as vector<double>&
}
in.clear();
...

现在,在书中以及cplusplus.com上都引用了clear函数重置所有错误状态的信息,并且输入现在又准备好读取某些输入.问题是,如果我输入:

Now, in book and also on the cplusplus.com refernce is stated that the clear function resets all the error states and that the input is now again ready to read some input.The problem is that if I put a:

int a = 0;
cin >> a;
cout << a << endl;

在该函数之后,它会跳转cin并给我一个0.我是否完全理解cin.clear()的功能,或者该怎么做才能使cin再次活跃.

after the function it jumps the cin and just gives me a 0. Did I understand the function of cin.clear() totally wrong or what can I do to get the cin active again.

由于在阅读本书之前,我遇到了同样的问题,所以我知道我可以通过以下代码解决问题:

As I had the same problem a while before I read the book, I know that I solved the problem back then with the following line:

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

当然,我必须再敲一个Enter键,但它会吃掉之前出现的所有东西,从而使cin无法正常工作.

Of course I then have to hit an extra enter key but it eats all the stuff which comes before and which makes the cin not to work.

问题是,.clear和.ignore都无法单独正常工作,但同时使用它们,我可以为变量a输入内容;

The thing is that neither .clear nor .ignore work properly alone but using them both together I am able to enter something for the variable a;

好的,这是完整的代码.这是我自己写的东西,不是书中的内容.

Ok, here is the whole code. This is something I have written myself, which is not from the book.

istream& in = cin;
int var = 0;
vector<int> vec;
while ( in >> var ) {
    vec.push_back(var);
}
for (int f = 0; f < vec.size(); ++f) {
    cout << vec[f] << endl;
}
cin.clear();
cout << "cleared" << endl;
    int a = 0;
    cin >> a;
    cout << a << endl;

推荐答案

clear 的调用将清除由于读取失败而设置的错误状态.对于输入流中可能存在的字符,它没有任何作用.

The call to clear clears the error state set by a failed read. It doesn't do anything with the characters that might be present in the input stream.

如果错误状态是由于未能读取双精度型而引起的,则下一个字符也可能作为整数而失败.

If the error state is a result of failing to read a double, it is likely that the next character will also fail as an integer.

如果您尝试

char ch;
cin >> ch;

我确信这会更好.

否则,您将不得不忽略一些字符以摆脱不可读的输入.

Otherwise you will have to ignore some characters to get rid of the unreadable input.

这篇关于有关cin.clear()的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:57