snprintf用法

1. 返回的是想要复制的字符串长度(不包括'\0'),如源字符串是"12",则返回2;如源字符串是"123",则返回3;而不管目标字符串的长度是多少.

2. 最多复制sizeof(dst)-1个字符,剩余的一个用'\0'补上.

 

#include<iostream>
#include<stdio.h>
using namespace std;

int main()
{
    char dst[3];
    int len = 0;

// 源字符串长度 <= sizeof(dst) - 1, 此时copy整个源字符串, 并在copy后的目的字符串后加'\0' len
= snprintf(dst, sizeof(dst), "1"); cout << "len=" << len << endl; cout << dst << endl;
len
= snprintf(dst, sizeof(dst), "12"); cout << "len=" << len << endl; cout << dst << endl;
// 源字符串长度 > sizeof(dst) - 1, 此时copy sizeof(dst) - 1个源字符串中的字符到目标字符串,并在目标字符串后加'\0' len
= snprintf(dst, sizeof(dst), "123"); cout << "len=" << len << endl; cout << dst << endl; len = snprintf(dst, sizeof(dst), "1234"); cout << "len=" << len << endl; cout << dst << endl; return 0; }

 

len=1
1
len=2
12
len=3
12
len=4
12

posted @ 2014-05-22 23:10  helloweworld  阅读(1597)  评论(0编辑  收藏  举报