首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用snprintf()的Fencepost条件和可移植性?

使用snprintf()的Fencepost条件和可移植性?
EN

Stack Overflow用户
提问于 2011-07-07 03:55:10
回答 1查看 311关注 0票数 2

给定以下代码:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-07-07 04:08:10

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

击剑杆的条件都很好。你的printf并不是完全正确,在equals的情况下,它将被打印出来

代码语言:javascript
复制
The buffer was not large enough, we needed 215 but only had 215.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6602117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档