Search code examples
c++cprintfstderr

C++ equivalent of fprintf with error


If I have an error message called by:

if (result == 0)
{
    fprintf(stderr, "Error type %d:\n", error_type);
    exit(1);
}

Is there a C++ version for this? It seems to me that fprintf is C rather than C++. I have seen something to do with cerr and stderr, but no examples that would replace the above. Or maybe I'm entirely wrong and fprintf is standard in C++?


Solution

  • All [with a few exceptions where C and C++ collide with regards to standard] valid C code is technically also valid (but not necesarrily "good") C++ code.

    I personally would write this code as :

    if (result == 0) 
    {
       std::cerr << "Error type " << error_type << std:: endl;
       exit(1);
    }
    

    But there are dozens of other ways to solve this in C++ (and at least half of those would also work in C with or without some modification).

    One quite plausible solution is to throw an exception - but that's only really useful if the calling code [at some level] is catch-ing that exception. Something like:

    if (result == 0)
    {
        throw MyException(error_type);
    }
    

    and then:

    try
    {
      ... code goes here ... 
    }
    catch(MyException me)
    {
        std::cerr << "Error type " << me.error_type << std::endl;
    }