while (1)
{
cout << "Enter the Citizen ID number of the worker or Enter 0 to exit:" << endl;
getline (cin, j);
for (i=0; i<5; i++)
{
if (workers[i]->IDno == j)
{
wFind = 1;
cout << "Choose your option:" << endl;
cout << "1- Display all details of the worker" << endl;
cout << "2- Display number of the days worker delayed" << endl;
cout << "3- Display number of the days worker missed" << endl;
cin >> k;
switch (k)
{
case 1:
workers[i]->AWorker();
break;
case 2:
cout << workers[i]->TotalDaysDelayed() << endl;
break;
case 3:
cout << workers[i]->TotalDaysMissed() << endl;
break;
default:
break;
}
}
else
wFind = 0;
}
if (wFind == 0)
cout << "ERROR: No worker has the ID number that you typed!" << endl;
}
注:wFind
初始化爲2
。循環在獲得輸入前完成一個循環,如何解決?
當我執行這個代碼,我總是得到這樣的輸出:
Enter the Citizen ID number of the worker or Enter 0 to exit:
ERROR: No worker has the ID number that you typed!
Enter the Citizen ID number of the worker or Enter 0 to exit:
有趣的是,我的代碼可以讓我輸入的字符串j
之前完成循環週期。這怎麼可能,我能做些什麼來解決它?
你可能想要清除使用getline和cin之間的輸入緩衝區。有時你會在那裏得到一些空白,它會打破進一步的輸入,特別是整數。它並不漂亮,但以下工作適合我:'while(cin.peek()<''){cin.ignore(1); }' –
不要混合標記提取('>>')和行讀取('getline')。 –