One you detect the error (either by checking the stream's state after >> returns, or by using istream::exceptions() to throw an exception on failure), then clear() the error, discard the bad input, prompt the user for good input, and then try to read again. Repeat if needed.
std::istream& operator>>(std::istream& is, Music& m)
{
do
{
try
{
if (is >> m.leng)
break;
}
catch (std::ios_base::failure& e)
{
}
is.clear();
is.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
std::cout << "enter a valid integer" << std::endl;
}
while (true);
is >> m.name;
return is;
}
Though, I really do not recommend this approach. If your >> fails to read in a Music, let it fail. The caller should be the one to deal with the failure as needed, not your >>. Your original code was fine as-is.
is >>m.lengcould not read anintthenif(!is){}allows you to do error handling. That can be done in the caller of your input stream operator.do { is >> m.leng >> m.name; try { if (!is) throw string("Error"); } catch (string& e) { cout << e << endl; } } while (!is); return is;