本文已参与「新人创作礼」活动,一起开启掘金创作之路。
1.1 printf(将数据打印到屏幕上)
向标准输出流(stdout)精选格式化输出的函数
例子
#include<stdio.h>
int main()
{
printf("hello\n");
int i=100;
printf("%d\n",i);
return 0;
}
1.2 scanf(从键盘获取数据)
从标准输入流(stdin)上进行格式化输入的函数
例子
#include<stdio.h>
int main()
{
int n = 0;
scanf("%d", &n);
char arr[100] = { 0 };
scanf("%c", arr);
return 0;
}
2.1 fprintf(将数据打印到文件中)
把数据按照格式化的方式输出到标准输出流(stdout)/指定文件流
举个例子:
#include<stdio.h>
#include<errno.h>
struct Stu
{
char name[20];
int age;
double score;
};
int main()
{
struct Stu s = { "zhangsan", 20, 95.5 };
FILE *pf = fopen("data.txt", "w");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
//写格式化的数据
fprintf(pf, "%s %d %lf", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
2.2 fscanf(从文件中获取数据)
可以从标准输入流(stdin)/指定的文件流上读取格式化的数据
举个例子:
#include<stdio.h>
#include<errno.h>
struct Stu
{
char name[20];
int age;
double score;
};
int main()
{
struct Stu s = {0};
FILE *pf = fopen("data.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
//读取格式化的数据
fscanf(pf,"%s %d %lf", s.name, &s.age, &s.score);
printf("%s %d %lf", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
3.1 sprintf(将结构体数据转化成字符串)
把一个格式化数据转化成字符串
struct Stu
{
char name[20];
int age;
double score;
};
int main()
{
struct Stu s = { "张三", 20, 95.5 };
char buf[100] = { 0 };
sprintf(buf,"%s %d %lf", s.name, s.age, s.score);
printf("%s\n", buf);
return 0;
}
3.2 sscanf(将字符串中内容转变成结构体信息)
可以从一个字符串中提取(转化)出格式化数据
struct Stu
{
char name[20];
int age;
double score;
};
int main()
{
struct Stu s = { "张三", 20, 95.5 };
struct Stu tmp = { 0 };
char buf[100] = { 0 };
sprintf(buf,"%s %d %lf", s.name, s.age, s.score);
printf("%s\n", buf);
sscanf(buf, "%s %d %lf", tmp.name, &tmp.age, &tmp.score);
printf("%s %d %lf\n", tmp.name, tmp.age, tmp.score);
return 0;
}