scanf printf
scanf: 按照一定的格式从键盘上输入数据
printf : 按照一定的格式把数据打印到屏幕上
格式化的输入输出语句
最基本的输入输出,需要格式化类型,按照类型输出
scanf需要取地址&,printf根据后面的要求按照格式打印
fscanf fprintf
fscanf:按照一定的格式从输入流(文件/stdin)输入数据
fprintf:按照一定的格式向输出流(文件/stdin)输出数据
适用于所有的输入/输出流的格式化输入输出语句
struct S {
char name[20];
int age;
float score;
};
int main() {
struct S s = { "zhangsan",19,99.50f };
FILE*pf=fopen("text.txt", "w");//创建并打开文件text.txt文件,进行写操作
if (NULL == pf) {
perror("fopen");
return 1;
}
//写文件
fprintf(pf, "%s %d %f", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
}
相对路径下创建了text.txt文件
写入了信息
struct S {
char name[20];
int age;
float score;
};
int main() {
struct S s = {0};
FILE* pf = fopen("text.txt", "r");//打开文件text.txt文件,进行读操作
if (NULL == pf) {
perror("fopen");
return 1;
}
//写文件
fscanf(pf, "%s %d %f", s.name, &(s.age), &(s.score));
printf("%s %d %f", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
}
读文件
sscanf sprintf
sscanf:从字符串中按照一定的格式读取格式化的数据
sprinft:把格式化的数据按照一定的格式转换成字符串
sprintf将结构体数据转化为字符串,放进buf数组中,并打印
#include<stdio.h>
struct S {
char name[20];
int age;
float score;
};
int main() {
struct S s = { "zzg",21,85.5f };
char buf[100] = { 0 };
//结构体数据转化为字符串
sprintf(buf, "%s %d %f", s.name, s.age, s.score);
printf("%s ", buf);
return 0;
}
字符串还原回结构体的格式
#include<stdio.h>
struct S {
char name[20];
int age;
float score;
};
int main() {
char buf[100] = { 0 };
struct S s = { "zzg",21,85.5f };
struct S tmp = { 0 };
//结构体数据转化为字符串
sprintf(buf,"%s %d %f", s.name, s.age, s.score);
printf("%s ", buf);
printf("\n");
//字符串还原成结构体
sscanf(buf,"%s %d %f", tmp.name, &(tmp.age), &(tmp.score));
printf("%s %d %f\n", tmp.name, tmp.age, tmp.score);
return 0;
}