#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'),返回值为欲写入的字符串长度。

 

posted on 2016-08-29 18:38  情月  阅读(1206)  评论(0编辑  收藏  举报