谢谢@yes2大佬的分析解读,您的指点提醒我在循环内增加了显示输入流条件状态的两行代码,修改如下:
[C++] 纯文本查看 复制代码 #include <iostream>
using namespace std;
int main()
{
char arr[10];
int a;
for (int i = 0; i < 2; ++i) {
cin.get(arr, 10); // 将 a = cin.get(arr, 10).get()拆开,分别查看get成员函数执行后cin的状态
cout << "第" << i + 1 << "次循环cin.get(arr, 10)之后:" << endl;
cout << "cin.eof--->" << boolalpha << cin.eof() << endl;
cout << "cin.fail--->" << cin.fail() << endl;
a = cin.get();
cout << "第" << i + 1 << "次循环接着cin.get()之后:" << endl;
cout << "cin.eof--->" << cin.eof() << endl;
cout << "cin.fail--->" << cin.fail() << noboolalpha << endl;
cout << a << endl;
for (size_t i = 0; i < 10; ++i)
cout << arr[i];
cout << "z" << endl;
}
return 0;
}
运行结果说明第二次循环时,cin.get(arr, 10, '\n')读完\n之后,因为缓冲区里再无内容,输入流的failbit被置位(奇怪的是eofbit并没有被置位),由于failbit被置位才返回了-1。是不是badbit, failbit和eofbit任一个被置位,cin.get()就会返回-1?
再次感谢大佬的热心解答 |