gpt4 book ai didi

c++ - 使用 snprintf() 的 Fencepost 条件和可移植性?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:34:47 25 4
gpt4 key购买 nike

给定以下代码:

const int size = 20;
char buffer[size];

// From the Linux man page for snprintf():
//
// The 'res' is the number of bytes that would be written to buffer had size been
// sufficiently large excluding the terminating null byte. Output bytes beyond
// the size-1st are discarded instead of being written to the buffer, and a null
// byte is written at the end of the bytes actually written into the buffer.
int res = snprintf(buffer, size, "some format with %d and %s", 23, "some string");

if (res >= size) {
cerr << "The buffer was not large enough, we needed " << res
<< " but only had " << size << "." << endl;
} else {
cout << "The buffer is big enough, we only needed " << res
<< " but had " << size << "." << endl;
}

这是可移植的吗?如果是,我是否正确设置了所有栅栏柱条件?

1 将 size 传递给 snprintf()

2 检查 res 是否大于或等于 size

最佳答案

snprintf 严格来说不是可移植的,因为它不是 C/C++ 标准的一部分。 Windows 将其命名为 _snprintf - 但其他方面相同。

fencepost 条件都很好。您的 printf 并不完全正确,在 equals 情况下它将打印

The buffer was not large enough, we needed 215 but only had 215.

关于c++ - 使用 snprintf() 的 Fencepost 条件和可移植性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6602117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com