【11】C实战篇——C语言 【scanf、printf、fprintf、fscanf、sprintf、sscanf】的区别

文章目录

  • 4 格式化输入输出
    • 4.1 格式化写 fprintf
    • 4.2 格式化读 fscanf
    • 4.3 数据转化为字符串 sprintf
    • 4.3 字符串的数据还原 sscanf

4 格式化输入输出

前边介绍的方法都是字符的读写,

fprintffscanf是对数据进行格式读写,

除此之外还有sscanfsprintf

我们可以来对比一下这几个函数:

  • scanf 从标准输入流读取格式化的数据。
  • printf 向标准输出流写格式化的数据。
  • fscanf 适用于所有输入流的格式化输入函数
  • fprintf 适用于所有输出流的格式化输出函数
  • sprintf 将格式化的数据写入到字符串中(将格式化的数据转化为字符串),可以将任何类型的数据转换成字符串;
  • sscanf将转换成字符串的数据还原 ,(sprintf将数据转换成字符串,sscanf将数据还原。)

4.1 格式化写 fprintf

fprintf 适用于所有输出流的格式化输出函数

cpp 复制代码
#include<stdio.h>

struct S {
	int a;
	float s;
};

int main()
{
	FILE* pf = fopen("data.txt", "w");//注意,读写时操作不同,注意修改
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	struct S s = { 100,3.14f };
	//写入到文本
	fprintf(pf, "%d %f", s.a, s.s);

	fclose(pf);
	pf = NULL;
	return 0;
}

它可以将不同格式的数据输出到指定位置。fprintfprintf很类似,就是前边加上输出的位置。

运行成功后,打开文件就可以看到100,3.140000出现在文件中。

4.2 格式化读 fscanf

fscanf 适用于所有输入流的格式化输入函数。

既然有格式化输出,那就必然有从文件中输入。

cpp 复制代码
struct S {
	int a;
	float s;
};

int main()
{
	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	struct S s = { 0 };
	fscanf(pf, "%d %f", &(s.a), &(s.s));
	printf("%d %f", s.a, s.s);
	fclose(pf);
	pf = NULL;
	return 0;
}

读取之前保存的数据,屏幕上就会输出文件中的数据。

fscanf和我们经常适用的scanf也很相似,只是多了一个读取数据的位置。

4.3 数据转化为字符串 sprintf

sprintf 将格式化的数据写入到字符串中(将格式化的数据转化为字符串),可以将任何类型的数据转换成字符串;

cpp 复制代码
struct S {
	int a;
	float s;
	char str[20];
};
int main()
{
	char ch[30] = { 0 };
	struct S s = { 100,3.14f,"hello world" };
	sprintf(ch, "%d %f %s", s.a, s.s, s.str);
	return 0;
}

通过调试,观察ch中的数据:

可以观察到它确实将数据转化成了字符串,并存放到了数组当中。

sprintfprintf也很类似,只需在前边添加要存放的数组。

4.3 字符串的数据还原 sscanf

sprintf 将数据转换成字符串,sscanf将数据还原。通过结构体访问成员进而输出。

cpp 复制代码
struct S {
	int a;
	float s;
	char str[20];
};
int main()
{
	char ch[30] = { 0 };
	struct S s = { 100,3.14f,"hello world" };
	struct S t = { 0 };
	sprintf(ch, "%d %f %s", s.a, s.s, s.str);

	sscanf(ch, "%d %f %s", &(t.a), &(t.s), &(t.str));
	printf("%d %f %s\n", t.a, t.s, t.str);
	return 0;
}

sscanf其实也是和scanf很像,它仅仅是在前边添加了一个转换的数组地址。

相关推荐
laocooon5238578861 小时前
一个适合新手的训练C题
c语言·开发语言
坚持编程的菜鸟2 小时前
LeetCode每日一题——缀点成线
c语言·算法·leetcode
degen_2 小时前
PEIM安装PPI和调用其他PPI的相关函数
c语言·笔记
啊森要自信3 小时前
【MySQL 数据库】使用C语言操作MySQL
linux·c语言·开发语言·数据库·mysql
yuuki2332333 小时前
【C语言】预处理详解
c语言·windows·后端
小立爱学习3 小时前
Linux 内存 --- get_user_pages/pin_user_pages函数
linux·c语言
GilgameshJSS4 小时前
STM32H743-ARM例程26-TCP_CLIENT
c语言·arm开发·stm32·单片机·tcp/ip
杨福瑞4 小时前
数据结构:顺序表讲解(1)
c语言·开发语言·数据结构
程序猿编码4 小时前
轻量级却实用:sigtrace 如何靠 ptrace 实现 Linux 信号的捕获与阻断(C/C++代码实现)
linux·c语言·c++·信号·捕获·ptrace
LaoZhangGong1235 小时前
IR红外遥控器和接收器
c语言·遥控器·红外·ir