scamf函数:int scanf(const char *format, ...);
当程序中调用
scanf()
的时候,终端会被阻塞,等待用户输入数据,此时我们可以通过键盘输入一些字 符,譬如数字、字母或者其它字符,输入完成按回车即可!接着来 scanf()
函数就会对用户输入的数据进行格式转换处理。
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
fscanf函数:int fscanf(FILE *stream, const char *format, ...);
fscanf()
函数从指定文件中读取数据,作为格式转换的输入数据,文件通过
FILE
指针指定,所以它有两 个固定参数,FILE
指针和格式控制字符串
format
。譬如从标准输入文件中读取数据进行格式化转换:
int a, b, c;
fscanf(stdin, "%d %d %d", &a, &b, &c);
此时它的作用与
scanf()
就是相同的,因为标准输入文件的数据就是用户输入的数据,譬如通过键盘输 入的数据。
也可以用打开文件的方式来获取数据,如下图:
int main(void)
{
int a,b,c;
FILE * fp = NULL;
if(NULL == (fp = fopen("./1.txt","r+")))
{
perror("fopen erroe");
exit(-1);
}
fscanf(fp,"%d %d %d",&a,&b,&c);
printf("a == %d b = %d c = %d\n",a,b,c);
fclose(fp);
return 0;
}
1.txt里面存放如下图
执行结果:
ssconf函数:int sscanf(const char *str, const char *format, ...);
sscanf()
将从参数
str
所指向的字符串缓冲区中读取数据,作为格式转换的输入数据
代码示例
char *str = "5454 hello";
char buf[10];
int a;
sscanf(str, "%d %s", &a, buf);
printf("a == %d buf == %s",a,buf);