c语言函数sscanf()和sprintf()

来源:互联网 发布:网络社交平台的特点 编辑:程序博客网 时间:2024/05/17 23:36
I.sscanf()头文件:#include<stdio.h>sscanf()函数用于从字符串中读取指定格式的数据,其原型如下:    int sscanf (char *str, char * format [, argument, ...]);参数说明:参数str为要读取数据的字符串;format为用户指定的格式;argument为变量,用来保存读取到的数据。函数返回值:成功则返回参数数目,失败则返回-1,错误原因存于errno 中。sscanf()会将参数str 的字符串根据参数format(格式化字符串)来转换并格式化数据(格式化字符串请参考scanf()), 转换后的结果存于对应的变量中。sscanf()与scanf()类似,都是用于输入的,只是scanf()以键盘(stdin)为输入源,sscanf()以固定字符串为输入源。例如:按照指定的格式从字符串中提取数据(注意;格式要与字符串格式一致,不然会出现不可预料的错误);#include<stdio.h>#include<stdlib.h>#include<string.h>#define _CRT_SECURE_NO_WARNINGSint main(int argc,char **argv){    char buf[]={"a = 10,b = 20,c = 30"};    int a,b,c;    sscanf(buf,"a = %d,b = %d,c = %d",&a,&b,&c);    printf("a = %d\nb = %d\nc = %d\n",a,b,c);    system("pause");    return 0;}打印结果为:a = 10b = 20c = 30sscanf(buf,"a = %d,b = %d,c = %d",&a,&b,&c);中格式换为sscanf(buf,"a=%d,b=%d,c=%d",&a,&b,&c);则会出现乱码,提取失败;(去掉了空格);sscanf()提取整型是最方便,只需要一个字符分隔即可;若要提取字符串,最好是以空格来分格;#include<stdio.h>#include<stdlib.h>#include<string.h>#define _CRT_SECURE_NO_WARNINGSint main(int argc,char **argv){    char buf[]={"hello world welcome"};    char str1[10] = {0};    char str2[10] = {0};    char str3[10] = {0};    sscanf(buf,"%s %s %s",str1,str2,str3);    printf("%s\n%s\n%s\n",str1,str2,str3);    system("pause");    return 0;}II.sprint()函数头文件:#include <stdio.h>sprintf()函数用于将格式化的数据写入字符串,其原型为:    int sprintf(char *str, char * format [, argument, ...]);参数说明:str为要写入的字符串;format为格式化字符串,与printf()函数相同;argument为变量。该函数的前两个参数类型固定,后面可以接任意多个参数。 sprintf()使用格式化字符串来指定串的格式,在格式串内部使用一些以“%”开头的格式说明符(format specifications)来占据一个位置,在后边的变参列表中提供相应的变量,最终函数就会用相应位置的变量来替代那个说明符,产生一个调用者想要的字符串。函数返回值:成功则返回参数str 字符串长度,失败则返回-1,错误原因存于errno 中例如:将整数a,b,c输出到字符数组中,而不是打印到终端(屏幕)上;#include<stdio.h>#include<stdlib.h>#include<string.h>#define _CRT_SECURE_NO_WARNINGSint main(int argc,char **argv){    int a = 100;    int b = 200;    int c = 300;    char buf[100] = {0};    sprintf(buf,"a = %d,b = %d,c = %d\n",a,b,c);    printf("%s\n",buf);    system("pause");    return 0;}打印结果:a = 100,b = 200,c = 300注意:sprintf的第一个参数应该是目的字符串,如果不指定这个参数,执行过程中会出现不可预知的错误;
1 0
原创粉丝点击