这是硬件。我问过我的教授为什么下面的代码不会退出 while 循环,他/她不能告诉我。我的理解是,一旦输入流没有更多值要读取,cin 将返回 false 值,并且应该导致 while 循环退出。我的没有。它似乎通过循环继续读取输入值(一组整数)过程,然后等待更多输入。谁能告诉我为什么?下面是代码。
# include <iostream>
using namespace std;
int main()
{
int iEvenSum = 0;
int iOddSum = 0;
int iNum;
// prompt user
cout << "Input any set of integers, separated by a space:\n";
cin >> iNum;
cout << "You input: ";
while (cin)
{
cout << iNum << " ";
if (iNum % 2 == 0)
iEvenSum = iEvenSum + iNum;
else
iOddSum = iOddSum + iNum;
cin >> iNum;
}
cout << "\n\nThe sum of Even numbers is " << iEvenSum << "." << endl;
cout << "The sum of Odd numbers is " << iOddSum << "." << endl;
return 0;
}