关于scanf接受键盘输入的细节
2015-08-23 23:06
232 查看
先看段代码:
#include <stdio.h>
int main(int argc,const
char * argv[]) {
int a =
0, b =0, c =
0;
char d =
'a', e ='a';
scanf("%d",&a);
scanf("%d",&b);
scanf("%c",&d);
scanf("%c",&e);
printf("%d,%d,%c,%d",a,b,d,e);
return
0;
}
当键盘输入 a-->回车 后输出的结果是
0,0,a,10
为什么会出现这样的结果呢?
因为
scanf("%d",&a);
scanf("%d",&b);
当缓存里面存放的是字符(空格和回车除外),它将跳过接受,执行下一行指令
所以a,b的值为0,此时缓存里面存的是字符 ‘a’ ‘\n’ 当遇到
scanf("%c",&d);
scanf("%c",&e);
缓存里面此时正好存放的是它们需要的数据,所以d = 'a' e = '\n' ('\n' 的ascii值时10),所以结果为
a = 0,b = 0,d = a,e = 10
在看一段代码
#include <stdio.h>
int main(int argc,const
char * argv[]) {
int a =
0, b =0, c =
0;
char d =
'a', e ='a';
scanf("%d",&a);
scanf("%d",&b);
scanf("%c",&d);
scanf("%c",&e);
scanf("%d",&c);
printf("%d,%d,%d,%c.%d",a,b,d,e,c);
return
0;
}
现在键盘输入顺序这么来 回车-->1-->回车-->2-->回车-->a-->回车-->3-->回车 输出结果为
1,2,10,a,3
scanf("%d",&a);
回车 此时它不接受字符'\n',之后这个字符就不再在缓存里了,1-->回车后 a接受了1
scanf("%d",&b);
此时缓存中有一个字符‘\n’,它不接受,之后这个字符也没了,2-->回车后 b接受了2
scanf("%c",&d);
此时缓存中有一个字符‘\n’,d接受了‘
4000
\n’
scanf("%c",&e);
a-->回车后,此时缓存里有两个字符'a','\n' e接受了'a'
scanf("%d",&c);
此时缓存里有一个字符'\n',它不接受,3-->回车后,c接受了3;
('\n'
的ascii值时10),所以结果为
a = 1,d = 2,c = 10,e = a,c = 3
#include <stdio.h>
int main(int argc,const
char * argv[]) {
int a =
0, b =0, c =
0;
char d =
'a', e ='a';
scanf("%d",&a);
scanf("%d",&b);
scanf("%c",&d);
scanf("%c",&e);
printf("%d,%d,%c,%d",a,b,d,e);
return
0;
}
当键盘输入 a-->回车 后输出的结果是
0,0,a,10
为什么会出现这样的结果呢?
因为
scanf("%d",&a);
scanf("%d",&b);
当缓存里面存放的是字符(空格和回车除外),它将跳过接受,执行下一行指令
所以a,b的值为0,此时缓存里面存的是字符 ‘a’ ‘\n’ 当遇到
scanf("%c",&d);
scanf("%c",&e);
缓存里面此时正好存放的是它们需要的数据,所以d = 'a' e = '\n' ('\n' 的ascii值时10),所以结果为
a = 0,b = 0,d = a,e = 10
在看一段代码
#include <stdio.h>
int main(int argc,const
char * argv[]) {
int a =
0, b =0, c =
0;
char d =
'a', e ='a';
scanf("%d",&a);
scanf("%d",&b);
scanf("%c",&d);
scanf("%c",&e);
scanf("%d",&c);
printf("%d,%d,%d,%c.%d",a,b,d,e,c);
return
0;
}
现在键盘输入顺序这么来 回车-->1-->回车-->2-->回车-->a-->回车-->3-->回车 输出结果为
1,2,10,a,3
scanf("%d",&a);
回车 此时它不接受字符'\n',之后这个字符就不再在缓存里了,1-->回车后 a接受了1
scanf("%d",&b);
此时缓存中有一个字符‘\n’,它不接受,之后这个字符也没了,2-->回车后 b接受了2
scanf("%c",&d);
此时缓存中有一个字符‘\n’,d接受了‘
4000
\n’
scanf("%c",&e);
a-->回车后,此时缓存里有两个字符'a','\n' e接受了'a'
scanf("%d",&c);
此时缓存里有一个字符'\n',它不接受,3-->回车后,c接受了3;
('\n'
的ascii值时10),所以结果为
a = 1,d = 2,c = 10,e = a,c = 3
相关文章推荐
- 【摘】【编写可维护的JavaScript】判断javascript中的类型
- 验证控件
- 学习Spring必学的Java基础知识(7)----事务基础知识
- shell编程
- HDOJ 3665 Seaside(最短路--floyd)
- 【jQuery】仿淘宝五星评价打分的实现
- 快速排序算法C++实现
- 零基础学python-7.7 字符串格式化方法(2)
- 【转】Ensemble learning(集成学习)
- 零基础学python-7.7 字符串格式化方法(2)
- 字典数据类型-字典常见操作
- Mac环境下搭建PhoneGap环境【转载】
- CSS3114: @font-face 未能完成 OpenType 嵌入权限检查。权限必须是可安装的。
- [不断更新]前端工程师面试必备知识清单
- SDM对分频器输出信号相位噪声的影响
- python发送Email 带附件
- UVa 1613:K-Graph Oddity(BFS)
- SQL中的case when then else end用法
- css属性image-redering详解
- 黑马程序员--正则表达式