错误的 fprintf 的 C++ 等价物

C++ equivalent of fprintf with error

如果我有一条错误消息:

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

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

中的标准

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

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

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

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

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

所有 [除了 C 和 C++ 在标准方面发生冲突的少数例外] 有效的 C 代码在技术上也是有效的(但不一定 "good")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;
}

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 实现和实例。