2015-01-12 20 views
2

我正在編寫一個大學的銀行應用程序,我偶然發現了一個問題。舉個例子,我們的客戶類是一個方法。開關狀態反應錯誤方法getline後C++

void Customer::create_customer_data() { 
    cout << "Client' Address: "; 
    getline(cin, clientAddress); 
    cin.ignore(); 
    cout << "Client's birth date: "; 
    getline(cin, clientBirthDate); 
    cin.ignore(); 
    cout << "Client's telephone number: "; 
    getline(cin, clientTelephoneNumber); 
    cin.ignore(); 
    cin.clear(); } 

在主函數中,我有一個switch語句來處理用戶的選擇。

int main() { 
int choice, _globalClientNumber = 0; 
Customer a(_globalClientNumber); 
cout << "Welcome to bank manager 1.0!" << endl; 

do { 
    cout << "Main Menu"<< endl; 
    cout << "Create a new customer (1)" << endl; 
    cout << "Create a new account (2)" << endl; 
    cout << "Cash money into account (3)" << endl; 
    cout << "Cash money out of account (4)" << endl; 
    cout << "Transfer money between two accounts (5)" << endl; 
    cout << "See current status of a customer and its accounts (6)" << endl; 
    cout << "End Application (0)" << endl; 

    cout << "Choice: "; 
    cin >> choice; 

    switch (choice) { 
     case 1: 
      a.create_customer_data(); 
      break; 
     case 2: 
      a.create_new_account(); 
      break; 
     case 3: 
      a.cash_in(); 
      break; 
     case 4: 
      a.cash_out(); 
      break; 
     case 5: 
      a.transfer_money(); 
      break; 
     case 6: 
      a.print(); 
      break; 
     default: 
      break; 
    } 

    cout << endl; 
} 
while (choice != 0); 

return 0; } 

,我保持具有的問題是,由該方法create_customer_data寫在屏幕上的值正在由do-while循環處理。因此,如果create_customer_data中的clientTelephoneNumber不以0結尾,則主菜單將通過do-while循環顯示兩次。如果有人能告訴我我的錯誤在哪裏,我將不勝感激。

編輯:簡而言之:選擇變量被覆蓋並且do-while循環被執行一次,導致雙重打印菜單。

回答

1

我會說,你的cin需要刷新。

的答案可以在這裏找到: How do I flush the cin buffer?

+0

這個問題也可能與http://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-忽略讀後輸入 – Codor

+0

的確如此。但它得出了相同的結論 – Zaiborg

+0

它醒了!謝謝! – cookiemonster