2

给定以下代码:

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

4

1 回答 1

1

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

栅栏条件都很好。您的 printf 并不完全正常,在等于的情况下它将打印

The buffer was not large enough, we needed 215 but only had 215.
于 2011-07-06T20:08:09.517 回答