C ++相当于fprintf的错误

时间:2015-06-19 17:32:54

标签: c++ c printf stderr

如果我有一条错误消息:

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

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

4 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:3)

所有[除了少数例外情况,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 :(得分:2)

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

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

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

答案 3 :(得分:0)

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