2011-11-10 66 views
0
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之前完成循環週期。這怎麼可能,我能做些什麼來解決它?

+0

你可能想要清除使用getline和cin之間的輸入緩衝區。有時你會在那裏得到一些空白,它會打破進一步的輸入,特別是整數。它並不漂亮,但以下工作適合我:'while(cin.peek()<''){cin.ignore(1); }' –

+0

不要混合標記提取('>>')和行讀取('getline')。 –

回答

1

cin >> k;不會吃換行符。你需要調用std::getline之後才能使用換行符。

如果你在循環的第一次迭代時遇到了問題,那麼我會推測你的代碼在此之上,也不會吃掉換行符。

+0

之後調用'cin.ignore'會比使用'std :: getline'更高效和更簡潔。 – ildjarn