C++ alternative to perror()(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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 替代 perror()


基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01