码迷,mamicode.com
首页 > 其他好文 > 详细

snprintf 使用注意

时间:2016-08-29 19:37:18      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

 

#include <iostream>
#include <cstdio>  // 包含的头文件

using namespace std;

int main(int argc, char **argv)
{
    int theTargetShapeForEncoding = 7;
    int theParaLocationInformation = 5;

    char aCharFormat[2];   // 注意声明变量的大小,最好不要太小,如果为 1 的话, 那么是会出错的。 详细的请参考下面的函数解释。
//char aCharFormat[1]; // 如果声明为 1 , 那么后面的 std::cout ... 输出是空。 snprintf(aCharFormat, sizeof(aCharFormat), "%x", theTargetShapeForEncoding); std::cout << "XXXX aCharFormat = " << aCharFormat << std::endl; snprintf(aCharFormat, sizeof(aCharFormat), "%x", theParaLocationInformation); std::cout << "XXXX aCharFormat = " << aCharFormat << std::endl; return 0; }

头文件: #include <cstdio>

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

详解:

(1) 如果格式化后的字符串长度 < size,则将此字符串全部复制到str中,并给其后添加一个字符串结束符(‘\0‘);
(2) 如果格式化后的字符串长度 >= size,则只将其中的(size-1)个字符复制到str中,并给其后添加一个字符串结束符(‘\0‘),返回值为欲写入的字符串长度。

 

snprintf 使用注意

标签:

原文地址:http://www.cnblogs.com/AndyStudy/p/5819145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!