C++ 替代 perror()

2021-12-26 00:00:00 error-handling c errno c++ cross-language

我知道我们可以使用

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

相关文章