未签名的snprintf长附加一个逗号 [英] snprintf of unsigned long appending a comma

查看:112
本文介绍了未签名的snprintf长附加一个逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将无符号长转换为字符串,附加在它的最后一个逗号。当编译并运行测试code你可以在下面找到,我得到以下的输出:

I try to convert a unsigned long into a character string, appending a comma at the end of the it. When compiling and running the test code you can find below, I get the following output:

"1234," "1234"
"1234"

测试code是:

The test code is:

#include <cstdio>
#include <iostream>

int main () {

    unsigned long c = 1234;
    char ch[50];
    char ch1[50];

    sprintf(ch, "%lu,", c);
    std::cout << "\"" << ch << "\"" << " \"" << c << "\"" << std::endl;

    snprintf(ch1, 5, "%s", ch); 
    std::cout << "\"" << ch1 << "\"" << std::endl;

    return 1;
}

据我了解, CH 应该是长度为5,4位数加1逗号。

As far as I understand, ch should be of length 5, 4 digits plus 1 for the comma.

难道我错过一个额外加上一个终止字符?

Do I miss an extra plus one for the termination character?

干杯!

推荐答案

传递给的snprintf 的大小,包括终止空字符。虽然没有印它,它仍然需要在缓冲空间。

The size that is passed to snprintf includes the terminating null character. Although it is not printed, it still takes space in the buffer.

您应该通过的strlen(CH)+ 1 来代替。甚至更好,只是的sizeof(CH1)就足够了,因为你要填充缓冲区之前,以适应整个结果。

You should pass strlen(ch) + 1 instead. Or even better, just sizeof(ch1) will suffice since you want to accommodate the entire result before filling the buffer.

另外,还要确保目标缓冲区具有足够的大小,等于或大于传递给的snprintf 尺寸更大的始终。在特定情况下,它也很难发生,但一般你应该记住这一点。

Also make sure that the destination buffer is always of a sufficient size, equal to or greater than the size you pass to snprintf. In your particular case it can hardly happen, but in general you should keep that in mind.

这篇关于未签名的snprintf长附加一个逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆