c语言scanf fscanf sscanf

1.scanf

概念

scanf用于从键盘(标准输入流)中读取数据,会返回成功读取到数据的个数

stdin 为标准输入流,这里指从键盘输入的数据

比较简单,这里不多介绍了。

用法

#include<stdio.h>
int main()
{
    int a =0;
    scanf("%d",&a);
    printf("%d",a);
    return 0;

}

2.fscanf()

概念

可以看出,描述与scanf基本相同。

fscanf可以从所有流中读取数据,使用方法与scanf差不多

失败会返回EOF

用法

1.从文件中读取数据
int main()
{
	FILE* pf = fopen("text.txt", "r");//流的地址
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	int a;
	float b;
	char m[10];
	fscanf(pf, "%d %f %s", &a, &b, m);
	printf("%d %f %s", a, b, m);
	fclose(pf);
	pf = NULL;
	return 0;
}
2.从键盘读取数据

我们知道stdin是标准输入流。所以只需把stdin当成参数传进去就行

#include<stdio.h>
int main()
{
    int a =0;
    fscanf(stdin,"%d",&a);
    printf("%d",a);
    return 0;
}

3.sscanf

概念

对比可以看出,这个函数是从字符串中读取数据。

失败的话会返回EOF

用法

int main()
{
	char* str = "abcdefg 100 3.14";
	char s1[10];
	int a;
	float b;
	sscanf(str, "%s %d %f", s1, &a, &b);
	printf("%s %d %f", s1, a, b);
	return 0;
}

4.进阶用法

以sscanf举例

1.指定精度

2.指定读取范围

#include<stdio.h>
int main()
{

	char str1[20];
	char str2[20];
	sscanf("123456abcdedf789", "%[0-9]",str1);
	printf("str1=%s\n", str1);
	sscanf("123456abcdedf789", "%[0-9a-z]", str2);
	printf("str2=%s\n", str2);
	return 0;
}

[^a-z]不读取a-z中的字符

%*[a-z]%[1-9]  两次读取,第一次不反回,第二次返回。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值