sscanf及sprintf

在程序中,我们肯定会遇到许多处理字符串的操作,当然C++中的string类已经做了很好了,但是也不要忘了C中的sscanf和sprintf

这两个函数用法跟printf和scanf用法很相似,只不过数据源和数据目的地从标准输入输出转换成了内存中的字符串。

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

 1 /* sscanf example */
 2 #include <stdio.h>
 3 
 4 int main ()
 5 {
 6   char sentence []="Rudolph is 12 years old";
 7   char str [20];
 8   int i;
 9 
10   sscanf (sentence,"%s %*s %d",str,&i);
11   printf ("%s -> %d
",str,i);
12   
13   return 0;
14 }
int sprintf ( char * str, const char * format, ... );

 1 /* sprintf example */
 2 #include <stdio.h>
 3 
 4 int main ()
 5 {
 6   char buffer [50];
 7   int n, a=5, b=3;
 8   n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
 9   printf ("[%s] is a string %d chars long
",buffer,n);
10   return 0;
11 }
原文地址:https://www.cnblogs.com/lit10050528/p/4064213.html