cin使用的问题
代码如下:
int main( int argc, char **argv )
{
vector <int> ivec;
int i, j = 0;
int result = 0;
cout < < "Enter some integers: " < < endl;
while( cin > > i )
{
ivec.push_back(i);
}
cout < < "Enter the number you want to count: " < < endl;
cin.clear();
cin > > j;
result = count(ivec.begin(), ivec.end(), j);
cout < < "The number " < < j
< < " occurs " < < result
< < " times. " < < endl;
return EXIT_SUCCESS;
}
现在有两个问题:
(1)在循环赋值以后,如果使用一个字符作为结束,则后面的cin > > j; 操作无法执行。
(2)如果使用ctrl+Z 结束,如果在 ctrl+Z 之前使用空格作为间隔,情况就与(1)一样, 如果在ctrl+Z之前使用回车作为间隔,程序就可以正常执行。
为什么?
[解决办法]
cin.clear();后加上cin.ignore();清除缓冲区