zoukankan      html  css  js  c++  java
  • 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 发表评论
  • 相关阅读:
    C#中使用ADOMD.NET查询多维数据集
    Expression表达式树
    SqlBulkCopy 批量复制数据到数据表
    字符串、字符、字节以及bit位小结与疑问
    C#系统委托之Action And Func
    C#中委托演变的的三个阶段
    C# 类成员备忘
    C#函数参数
    MongoDB-Getting Started with the C# Driver
    为MongoDB创建一个Windows服务
  • 原文地址:https://www.cnblogs.com/liyuxia713/p/2540789.html
Copyright © 2011-2022 走看看