c++ - 安全地将 printf 打印到字符串的最佳方法?

标签 c++ stl

有没有人知道将 printf 样式函数的输出重定向到字符串的安全的好方法?显而易见的方式会导致缓冲区溢出。

类似:

string s;
output.beginRedirect( s );  // redirect output to s

... output.print( "%s%d", foo, bar );

output.endRedirect();

我认为这个问题与问“打印会产生多少个字符?”是一样的。 想法?

最佳答案

你可以使用:

std::snprintf如果您正在使用 char*

std::stringstream如果您想使用字符串(与 printf 不同,但可以让您使用普通的流函数轻松操作字符串)。

boost::format如果你想要一个类似于 printf 的函数来处理流。 (根据评论中的jalf)

fmt::format自 c++20 std::format 起已标准化

关于c++ - 安全地将 printf 打印到字符串的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/436367/

相关文章:

c++ - 使用 'using' 关键字使继承的构造函数公开

c++ - 如何使用插槽实时更新 paint()

c++ - iOS 如何将 C++ 对象存储到用作 TableView 数据源的 NSArray

c++ - std::vector 和 c 风格数组

c++ - 无法通过命令行禁用 OpenCV/MSVC C4265(无虚拟析构函数)错误

c++ - 在没有正则表达式的情况下选择特定的字符串模式

c++ - 是否可以使用 std::basic_string 作为 char* 的包装器?

c++ - 为什么 std::pair 没有迭代器?

c++ - 为什么当我删除 std::vector 的成员时我的程序崩溃

c++ - std::sort 在 std:vector of pointers 上失败