C++ 替代 perror() [英] C++ alternative to perror()

查看:60
本文介绍了C++ 替代 perror()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以使用

perror()

在 C 中打印错误.我只是想知道是否有 C++ 替代方案,或者我是否必须在我的程序中包含这个(以及因此 stdio.h).我尽量避免使用 C 函数.

in C to print errors. I was just wondering if there is a C++ alternative to this, or whether I have to include this (and therefore stdio.h) in my program. I am trying to avoid as many C functions as possible.

推荐答案

你可以这样做:

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

这最终仍然会调用 strerror,因此您实际上只是用一个 C 函数替换了另一个.OTOH,它确实让你通过流编写,而不是混合 C 和 C++ 输出,这通常是一件好事.至少 AFAIK,C++ 没有在库中添加任何东西来代替 strerror(除了生成 std::string,我不确定是什么无论如何,它会从 strerror 改变.

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).

这篇关于C++ 替代 perror()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆