首先上原文链接☀️光天化日学C语言☀️(05)- 格式化输入 | 恭喜你,你应该可以做一款独立游戏了_英雄哪里出来-CSDN博客
一、概念原理
1. 标准输入
在C语言中,有三个函数可以用来在键盘上输入数据:
1)gets() :用于输入一行字符串;
2)getchar() :用于输入单个字符;
3)scanf():可以输入各种类型的数据
2. 格式化输入
scanf
的函数的命名含义是:Scan(扫描) 和 Format (格式) ,即 格式化输入。- 和输出一样,输入的时候,也根据数据类型的不同,分为 整数、浮点数、字符、字符串等等。
- 对于单个数据的输入,注意代码段中的&和\n。
-
#include <stdio.h> int main() { int a; scanf("%d", &a); printf("%d\n", a); return 0; }
- 两个数据的输入,需要用两次scanf函数:
-
#include <stdio.h> int main() { int a, b; scanf("%d", &a); scanf("%d", &b); printf("%d %d\n", a, b); return 0; }
- 或者一个scanf
-
#include <stdio.h> int main() { int a, b; scanf("%d %d", &a, &b); printf("%d %d\n", a, b); return 0; }
3. 回车结算
scanf()
是以回车来结算一次输入的。用户每次按下回车键,计算机就会认为完成一次输入操作,scanf()
开始读取用户输入的内容,并根据我们定义好的格式化内容从中提取有效数据,只要用户输入的内容和格式化内容匹配,就能够正确提取。- 我用的IDE是CodeBlocks
- 输入以下代码
-
#include <stdio.h> int main() { int a = 9, b = 8, c = 7, d = 6, e = 5; scanf("%d %d %d %d", &a, &b, &c, &d); printf("%d %d %d %d\n", a, b, c, d); scanf("%d", &e); printf("%d\n", e); return 0; }
-
得到如下结果
4. 字符串的输入
- 字符串输入时
&
可以不加,但要先定义一个数组 -
#include <stdio.h> int main() { char str[100]; scanf("%s", str); printf("%s\n", str); return 0; }
二、解题练习
1.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int t;
printf("input the input times:\n");
scanf("%d",&t);
int a, b;
while(t--){
printf("enter two integers:\n");
scanf("%d %d",&a,&b);
printf("sum = %d\n", a+b);
}
return 0;
}
这里while值得注意:
2.
#include <stdio.h>
int main() {
int a, b;
while(scanf("%d %d", &a, &b) != EOF) {
printf("%d\n", a + b);
}
return 0;
}
最后,由于是学习报告,所以内容多是转载
————————————————
版权声明:本文为CSDN博主「英雄哪里出来」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/WhereIsHeroFrom/article/details/117897684