问题描述
我问过关于strncpy
的相同问题,但是string
最终包含了全部内容输入字符串.将字符串传递给vsnprintf
时,最后一个字符总是会被砍掉: https://rextester.com/UIQMX91570
I've asked the same question about strncpy
, but there the string
ends up containing the whole input string. When passing a string to vsnprintf
the last character always gets chopped off: https://rextester.com/UIQMX91570
为简单起见,我还在代码的内联上方包含了实时示例链接:
For simplicity I've also included the live example link above inline in the code:
void bar(const char* format, va_list vlist) {
const auto buf_size = vsnprintf(nullptr, 0U, format, vlist);
string buffer(buf_size, '\0');
vsnprintf(data(buffer), buf_size, format, vlist);
cout << data(buffer) << endl;
}
void foo(const char* format, ...) {
va_list vlist;
va_start(vlist, format);
bar(format, vlist);
va_end(vlist);
}
如果我用foo("lorem ipsum %d", 13)
进行调用,我得到的输出是:
If I call this with: foo("lorem ipsum %d", 13)
the output I get is:
如我所料:lorem ipsum 13
Where as I would have expected: lorem ipsum 13
谁能解释这个差异?当我调试时,得到的buf_size
为14,其中应该足以包含整个字符串,但它不是:(
Can anyone explain the discrepancy? When I debug I get a buf_size
of 14 which should be enough to contain the entire string, yet it does not :(
推荐答案
因为他们记录的行为不同.
Because their documented behavior is different.
但是 vsnprintf()
强调是我的.
这篇关于为什么vsnprintf不写与strncpy相同数量的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!