There's plenty of ways around the many problems associated with
cin >>; IMHO the best way to avoid them is to never use the
>> operator in conjunction with
cin in the first place (unless its really necessary).
My personal preference is to keep a separate function which grabs a line using
getline(), and a stringstream to convert your input to whatever numeric type you need.
bool read_float( std::istream& in , float& num )
{
std::string str;
std::getline( in, str );
std::istringstream iss( str );
iss >> num;
return iss.good();
}
This has the added bonus of removing the risk that
cin will fail due to invalid chars being typed. You can check for this after asking the user to enter the price of the pie.
cout << "\nEnter price of pie:";
while ( ! read_float( std::cin , g ) )
std::cout << "Invalid input - Enter price of pie: ";
One slight nitpick - the default floating-point type in C++ is
double. For that reason its usually recommended to always use double whenever you need floating point numbers, unless you have some compelling reason otherwise to use float (which generally suffers from low precision. usually only 5 or 6 s.f. on most modern machines)
edit if you want to be extra-clever you can template the 'read' function to work with other numeric types (which would be handy if you wanted to do the same with int or double)
template <typename Ty>
bool read_in( std::istream& in , Ty& num )
{
std::string str;
std::getline( in, str );
std::istringstream iss( str );
iss >> num;
return iss.good();
}