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;
      }
   }

}
user4581301
  • 29,019
  • 5
  • 26
  • 45
  • What is your expected output, and what is your input that doesn't work? I tested your code snippet, and it seemed to work fine for me. – Algirdas Preidžius Oct 18 '15 at 16:57
  • Getline cannot get data that has already been gotten. Clear removes the error condition, but it does not allow you to re-get the data from the stream. – user4581301 Oct 18 '15 at 17:00

1 Answers1

0

Try this:

Read the whole line all the time. Then attempt to convert the line into a string. If it converts, return. Otherwise try again.

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: ";
       }
   }
}
user4581301
  • 29,019
  • 5
  • 26
  • 45