【问题标题】:C++ equivalent of fprintf with error与 fprintf 等效的 C++ 错误
【发布时间】:2015-06-19 17:32:54
【问题描述】:

如果我有错误消息调用:

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

这个有C++ 版本吗?在我看来fprintfC 而不是C++。我已经看到与cerrstderr 有关的内容,但没有可以替代上述内容的示例。或者我完全错了,fprintfC++ 中是标准的?

【问题讨论】:

  • 请不要使用exit(强制终止程序)
  • @DieterLücking:为什么不呢?据我了解,显示的代码是C代码。

标签: c++ c printf stderr


【解决方案1】:

所有 [除了 C 和 C++ 在标准方面发生冲突的少数例外] 有效的 C 代码在技术上也是有效的(但不一定是“好”)C++ 代码。

我个人会将这段代码写成:

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

但是在 C++ 中还有许多其他方法可以解决这个问题(其中至少有一半也可以在 C 中使用,无论是否进行一些修改)。

一个相当合理的解决方案是throw 一个异常 - 但这只有在调用代码 [在某种程度上] 是 catch 时才真正有用。比如:

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

然后:

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

【讨论】:

    【解决方案2】:

    您可能在您的第一个 Hello World 中听说过 std::cout!程序,但 C++ 也有一个std::cerr 函数对象。

    std::cerr << "Error type " << error_type << ":" << std::endl;
    

    【讨论】:

    • 像他一样打印到 stderr 也是可以接受的。
    • 可以接受,但很难打字安全。在我看来,只有当您的日志记录存在性能问题时,它才是合理的。当然,还有其他现代 C++ 库的性能与 printf 一样好,同时类型安全且比标准 iostream 更易于使用...
    【解决方案3】:

    C++ 中的等价物是使用std::cerr

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

    如您所见,它使用了您熟悉的用于其他流的典型 operator&lt;&lt; 语法。

    【讨论】:

      【解决方案4】:

      C++ 代码使用std::ostream 和文本格式操作符(不管它是否代表一个文件)

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

      要使用专用于文件的std::ostream,您可以使用std::ofstream

      stderr 文件描述符映射到std::cerr std::ostream 实现和实例。

      【讨论】:

        猜你喜欢
        • 2013-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-16
        • 2020-03-23
        • 1970-01-01
        • 2016-10-22
        相关资源
        最近更新 更多