C++:sscanf和sprintf的定义和使用

折月煮酒 提交于 2020-08-06 07:58:11

int sprintf ( char * str, const char * format, ... );

str - Pointer to a buffer where the resulting C-string is stored (should be large enough)
format - same as format in printf
... - additional arguments

return: strlen(str) - the total number of characters written

char buffer [50];
int id = 1234567;
int n = sprintf (buffer, "My ID is %d", id);

// buffer: My ID is 1234567
// n: 16

参考资料:http://www.cplusplus.com/reference/cstdio/sprintf/ 

int sscanf ( const char * s, const char * format, ...);

s - C string that the function processes as its source to retrieve the data.
format - same as format in scanf
... - additional arguments

return: the number of items in the argument list successfully filled.

char buffer [] = "Tom 18,7817";
char name[20];
int age, id;
sscanf(buffer, "%s %d,%d",name,&age,&id);
// s: Tom  age: 18  id: 7817

PS. sscanf虽然很强大,但是难以处理带空格的(或者空格不在开头结尾的)字符串。

请参考:C++字符串格式化输入——如何读入Tom Hanks,18,7817

参考资料:http://www.cplusplus.com/reference/cstdio/sscanf/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!