C++ equivalent of fprintf with error

3.9k views Asked by At

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++?

4

There are 4 answers

0
Mats Petersson On BEST ANSWER

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;
}
2
KABoissonneault On

You might have heard of std::cout in your first Hello World! program, but C++ also has an std::cerr function object.

std::cerr << "Error type " << error_type << ":" << std::endl;
0
Cory Kramer On

The equivalent in C++ would be to use std::cerr

#include <iostream>
std::cerr << "Error type " << error_type << ":\n";

which as you can see uses the typical operator<< syntax that you are familiar with for other streams.

0
πάντα ῥεῖ On

C++ code rather uses std::ostream and text formatting operators (regardless if it's representing a file or not)

void printErrorAndExit(std::ostream& os, int result, int error_type) {
    if (result == 0) {
        os << "Error type " << error_type << std::endl;
        exit(1);
    }
}

To use a std::ostream specialized for files, you can use std::ofstream.

The stderr file descriptor is mapped to the std::cerr std::ostream implementation and instance.