给定以下代码:
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
发布于 2011-07-07 04:08:10
严格地说,snprintf不是可移植的,因为它不是C/C++标准的一部分。Windows将其命名为_snprintf -但在其他方面完全相同。
击剑杆的条件都很好。你的printf并不是完全正确,在equals的情况下,它将被打印出来
The buffer was not large enough, we needed 215 but only had 215.https://stackoverflow.com/questions/6602117
复制相似问题