函数原型:int sprintf ( char * str, const char * format, ... );
函数功能:
使用示例:
char str[256] = { 0 }; int data = 1024; //将data转换为字符串 sprintf(str,"%d",data); //获取data的十六进制 sprintf(str,"0x%X",data); //获取data的八进制 sprintf(str,"0%o",data); const char *s1 = "Hello"; const char *s2 = "World"; //连接字符串s1和s2 sprintf(str,"%s %s",s1,s2);
示例程序:
/* sprintf example */ #include <stdio.h> int main () { char buffer [50]; int n, a=5, b=3; n=sprintf (buffer, "%d plus %d is %d", a, b, a+b); printf ("[%s] is a string %d chars long\n",buffer,n); return 0; } //OutPut : [5 plus 3 is 8] is a string 13 chars long
函数原型:int sscanf ( const char * s, const char * format, ...);
函数功能:
格式字符:
使用示例:
const char *s = "http://www.baidu.com:1234"; char protocol[32] = { 0 }; char host[128] = { 0 }; char port[8] = { 0 }; sscanf(s,"%[^:]://%[^:]:%[1-9]",protocol,host,port); printf("protocol: %s\n",protocol); printf("host: %s\n",host); printf("port: %s\n",port);
示例程序:
/* sscanf example */ #include <stdio.h> int main () { char sentence []="Rudolph is 12 years old"; char str [20]; int i; sscanf (sentence,"%s %*s %d",str,&i); printf ("%s -> %d\n",str,i); return 0; } //OutPut : Rudolph -> 12
转载自:http://www.cnblogs.com/Anker/p/3351168.html 和 cplusplus.com