liyuxia713

蹒跚前行者

常用链接

统计

Algorithms

C++

最新评论

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;

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

posted on 2010-04-25 19:23 幸运草 阅读(460) 评论(0)  编辑 收藏 引用 所属分类: C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理