C++ alternative to perror()

前端 未结 2 1376
夕颜
夕颜 2020-12-16 13:02

I know we can use

perror()

in C to print errors. I was just wondering if there is a C++ alternative to this, or whether I have to include

相关标签:
2条回答
  • 2020-12-16 13:33

    You could do something like:

    std::cerr << strerror(errno) << std::endl;
    

    That still ends up calling strerror, so you're really just substituting one C function for another. OTOH, it does let you write via streams, instead of mixing C and C++ output, which is generally a good thing. At least AFAIK, C++ doesn't add anything to the library to act as a substitute for strerror (other than generating an std::string, I'm not sure what it would change from strerror anyway).

    0 讨论(0)
  • 2020-12-16 13:39

    You could use the boost::system_error::error_code class.

    #include <boost/system/system_error.hpp>
    
    #include <cerrno>
    #include <iostream>
    
    void
    PrintError(
            const std::string& message,
            int error
            )
    {
        std::cerr << message << ": " <<
                boost::system::error_code(
                    error,
                    boost::system::get_system_category()
                    ).message()
                << std::endl;
    }
    
    int
    main()
    {
        PrintError( "something went wrong!", EINVAL );
        return 0;
    }
    

    it's a tad verbose, and somewhat overkill if you aren't already using the boost_system library.

    0 讨论(0)
提交回复
热议问题