snprintf 函数用法

原型:int snprintf(char *str, size_t size, const char *format, ...);

描述:The functions snprintf() write at most size bytes (including the terminating null byte ('\0')) to str. 即snprintf这个函数按照format格式最多将size个字符写入到str中,其中size个字符已经包括了结束符。

         很多时候,总没记住size这个参数是否包含结束符'\0',一般都填入size的参数就填str的大小减1了,这样肯定没错,只不过缓冲区中有一位肯定都用不上了。其实该函数内部已经对这些东西进行考虑了,我们只需要填入str的实际size就可以。

示例:

#include <iostream>
#include <string>

using namespace std;


void test()
 {
    char buf[8] = {0};
    snprintf(buf, 8, "%s", "helloworld!");
    cout << buf << endl;
}

int main()
{
    test();
    return 0;
}

输出结果如下:

hellowo


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值