代码之家  ›  专栏  ›  技术社区  ›  Sagar

C++替代PrRoR()

  •  15
  • Sagar  · 技术社区  · 15 年前

    我知道我们可以用

    perror()
    

    在C中打印错误。我只是想知道是否有C++的替代方案,或者我是否需要在程序中包含这个(因此STDIO?h)。我尽量避免使用C函数。

    谢谢!

    2 回复  |  直到 15 年前
        1
  •  20
  •   Jerry Coffin    15 年前

    你可以这样做:

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

    最后还是打电话来了 strerror ,所以您实际上只是用一个C函数替换另一个。OTHH,它可以让你通过流写,而不是混合C和C++输出,这通常是一件好事。至少,C++不给库添加任何东西来代替 斯特朗 (除了生成 std::string ,我不确定它会从什么变化 斯特朗 不管怎样)。

        2
  •  2
  •   Sam Miller    15 年前

    你可以用 boost::system_error::error_code 班级。

    #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;
    }
    

    这有点冗长,如果你还没有使用Boost_系统库的话,那就有点过分了。