• sprintf


    sprintf:  http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
     

    Portotype:  int printf(char* str, const char* format, parameters);

    Writes into the array pointed by str a C string consisting on a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format.

    This function behaves exactly as printf does, but writing its result to a string instead of stdout. The size of the array passed as str should be enough to contain the entire formatted string .

    Return value:

    On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string.

    //Success
    //The size of str is long enough
    //the number of additional number match with the format
    const int size = 25;
    char *str = new char[size]; 

       //same as int flag1 = sprintf(str,"%s is written to str.","Test","tEST");
    int flag1 = sprintf(str,"%s is written to str.","Test");
    //Console: 23-Test is written to str
    cout << flag1 << "-" << str << endl; 

    On failure, a negative number is returned.

    //Failure1
    //additional arguments numbers is less than specified is format
    //the second %s transmited as unrecognizable words
    const int size = 25;
    char *str = new char[size]; 
    int flag2 = sprintf(str,"%s %s tttttttttttt","Test");
    //Console: 19--Test @ tttttttttttt
    cout << flag2 << "--" << str << endl;


    //Failure2:the size of str is not long enough
       // 在dev c++不能运行,vc6.0沒有问题

    const int size = 25;
    char *str = new char[size]; 
    int flag3 = sprintf(str,"%s jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj","Test");
    //VC6.0 Console: Test jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
    //Dev c++: Console: the same as vc6.0 but throws an cannot read memory exception
    cout << flag3 << "--" << str << endl;


    没有测试出什么时候出错返回负值呢!!谁给我一个例子?


    幸运草 2010-04-25 19:23 发表评论
  • 相关阅读:
    Android Developers:使ListView滑动流畅
    Nexus 搭建maven 私有仓库
    Eclipse 配置Maven以及修改默认Repository
    maven常用命令介绍
    maven 相关
    session机制详解以及session的相关应用
    正确理解web交互中的cookie与session
    前端开发中Cookie那些事儿
    html转义表
    常用的Linux命令
  • 原文地址:https://www.cnblogs.com/liyuxia713/p/2540789.html
Copyright © 2020-2023  润新知