這是hw。我問過我的教授爲什麼下面的代碼不會退出while循環,而且他/她也不能告訴我。我的理解是,一旦輸入流沒有更多值要讀取,cin將返回false值,並應導致while循環退出。我的不是。它似乎保持通過循環讀取輸入值(一組整數)過程,然後等待更多輸入。誰能告訴我爲什麼?以下是代碼。while循環與cin的LCV不會在C++中退出
# 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;
}
你試圖讓循環停止?只需停止提供輸入不會改變任何內容:'cin'只是等待另一個輸入。 – Walter