scanf()与getchar()到底是怎么回事?

projoy 2008-09-01 11:12:34
为什么有的时候要在scanf()后面加一个getchar()才可以正常运行?难道是getchar()把回车吃了?说什么要清除缓冲区之类的,到底这是怎么回事?有没有避免的方法?
...全文
245 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
budweiser 2008-09-02
  • 打赏
  • 举报
回复
那 C语言 标准对此的推荐做法是什么呢?
e_sharp 2008-09-02
  • 打赏
  • 举报
回复
[Quote=引用 13 楼 projoy 的回复:]
那我有时候scanf时要一起输入好几个东西,有字符串,数字,字符,有时候要加好几个getchar()而且都是试验性质,不知道应该加多少,好困扰啊
[/Quote]

lz scanf()怎么写的? 贴出来看看,里面不要写'\n'
lsd1025 2008-09-02
  • 打赏
  • 举报
回复
UP,学习!
silverfoxyan 2008-09-01
  • 打赏
  • 举报
回复
等待
e_sharp 2008-09-01
  • 打赏
  • 举报
回复
我汗,怎么又是回复2次啊
e_sharp 2008-09-01
  • 打赏
  • 举报
回复
getchar 吃 回车
e_sharp 2008-09-01
  • 打赏
  • 举报
回复
getchar 吃 回车
cddeng814 2008-09-01
  • 打赏
  • 举报
回复
int fflush(FILE *stream);

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

hanxiao20 2008-09-01
  • 打赏
  • 举报
回复
建议在所有输入的前面加上
fflush(stdin);
保险
lbh2001 2008-09-01
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 lonecrystal 的回复:]
你在scanf加个\n也行
int ch;
scanf(%c\n", &ch);
[/Quote]
这个方法是错的,会造成scanf挂起
因为它读取一个字符后,期望读到一个非空白符,并不是读换行符的意思
cddeng814 2008-09-01
  • 打赏
  • 举报
回复
我晕 回车空格对于scanf来说是分割输入的
你要这样写才真的完了:
int ch;
scanf(%c\n", &ch);
不信自己试试
另外fflush(stdin)是不可移植的,标准没有规定对输入流做fflush操作
xqls_xqls 2008-09-01
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 lbh2001 的回复:]
难道是getchar()把回车吃了?

呵呵,你答对了
scanf会将不匹配的字符放回缓冲区,等待下一次读取
如不清除的话,scanf会一直读取回车,发现不匹配又放回缓冲区,等待下一次读取
[/Quote]
lonecrystal 2008-09-01
  • 打赏
  • 举报
回复
你在scanf加个\n也行
int ch;
scanf(%c\n", &ch);
冷月清晖 2008-09-01
  • 打赏
  • 举报
回复
也可以用
fflush( stdin );
lbh2001 2008-09-01
  • 打赏
  • 举报
回复
难道是getchar()把回车吃了?

呵呵,你答对了
scanf会将不匹配的字符放回缓冲区,等待下一次读取
如不清除的话,scanf会一直读取回车,发现不匹配又放回缓冲区,等待下一次读取
projoy 2008-09-01
  • 打赏
  • 举报
回复
那我有时候scanf时要一起输入好几个东西,有字符串,数字,字符,有时候要加好几个getchar()而且都是试验性质,不知道应该加多少,好困扰啊
ysysbaobei 2008-09-01
  • 打赏
  • 举报
回复
mark

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧