2015-10-18 54 views
0
// Validation and entry for ticket price 
void ValidateTicketPrice (double &ticket_price){ 

    string error_string; 

    cin >> ticket_price; 
    while(1) 
    { 
     if(cin.fail()) 
     { 
     cin.clear(); 
     getline (cin, error_string); 
     cout << error_string << " is not a valid ticket price. Please re-enter the data: "; 
     cin >> ticket_price; 
     } else { 
     Flush(); 
     break; 
     } 
    } 

} 
+0

您的預期輸出是什麼,您的輸入是什麼不起作用?我測試了你的代碼片段,它對我來說似乎很好。 –

+0

Getline無法獲取已獲取的數據。清除將刪除錯誤狀態,但不允許您從流中重新獲取數據。 – user4581301

回答

0

後並沒有得到某些字符試試這個:

閱讀全行所有的時間。然後嘗試將該行轉換爲字符串。如果它轉換,則返回。否則再試一次。

void ValidateTicketPrice (double &ticket_price){ 

    std::string input; 

    while(std::getline (std::cin, input)) 
    { 
     char * endp; 

     ticket_price = strtod(input.c_str(), &endp); 
     if (*endp == '\0') 
     { // number conversion and input ended at same place. Whole input consumed. 
      return; 
     } 
     else 
     { // number and strign did not end at the same place. bad input. 
      std::cout << input << " is not a valid ticket price. Please re-enter the data: "; 
     } 
    } 
}