C/C++ sprintf snprintf

int sprintf ( char * str, const char * format, ... );
int snprintf ( char * s, size_t n, const char * format, ... );

 snprintf是sprintf的升级版,加了一个参数n,有效防止写入字符串超过预期长度。

snprintf若成功则返回欲写入的字符串长度,若出错则返回负值。
sprintf的返回值是成功写入的字符串长度。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

int main()
{
    char *test = (char*)malloc(2);
    char *test1 = (char*)malloc(7);
    int i = snprintf(test,6,"%s","123456789");
    int j = sprintf(test1,"%s","123456789");
    printf("%s\n",test);
    printf("%s\n",test1);
    cout<<i<<"\n"<<j<<endl;
    return 0;
}
12345
123456789
9
9

Process returned 0 (0x0)   execution time : 0.027 s
Press any key to continue.

 

posted @ 2017-08-14 10:39  爱吃土豆的男孩  阅读(575)  评论(0编辑  收藏  举报