0

I want to handle the following error: imagine I start writing a string instead of an int and the defined overloading operator is this:

std::istream& operator>>(std::istream& is, Music& m)
{
    return is >> m.leng >> m.name;
}

so the first argument is an int and the second is a string but accidently I write a string how can I handle this error?

9
  • You can set up istream::exceptions. Commented May 12, 2020 at 15:46
  • I think you didn't understand what I mean I talk about simple input Commented May 12, 2020 at 15:51
  • 1
    If is >>m.leng could not read an int then if(!is){} allows you to do error handling. That can be done in the caller of your input stream operator. Commented May 12, 2020 at 15:58
  • @WernerHenze, how can I do if I want to restart the function in case of error, I mean I did like that but doesn't work: do { is >> m.leng >> m.name; try { if (!is) throw string("Error"); } catch (string& e) { cout << e << endl; } } while (!is); return is; Commented May 12, 2020 at 16:09
  • 1
    @Backik "I want to change it" - change what exactly? Please be more specific. Commented May 12, 2020 at 16:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.