鱼C论坛

 找回密码
 立即注册
查看: 2472|回复: 3

[已解决]要求输入整数,但输入了一个字母或符号,程序陷入死循环,怎么办?求解

[复制链接]
发表于 2019-4-6 22:06:06 | 显示全部楼层 |阅读模式
50鱼币
我在网上查了一下这个问题,但我并不想用fflush(stdin),
用while(getchar()!='\n')也不管用,
还有没有别的办法啊。。。
请那个大家可以留言。
感谢
最佳答案
2019-4-6 22:06:07
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. main(void)
  5. {
  6.         char buf[82]                                    ;
  7.         int n                                           ;
  8.         for(;;) {
  9.                 printf("input a integer please : ")     ;
  10.                 fgets(buf , 80 , stdin)                 ;
  11.                 if(sscanf(buf , "%d" , & n) == 1) break ;
  12.                 else printf("input error !\n")          ;
  13.         }
  14.         printf("n = %d\n" , n)                          ;
  15. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-4-6 22:06:07 | 显示全部楼层    本楼为最佳答案   
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. main(void)
  5. {
  6.         char buf[82]                                    ;
  7.         int n                                           ;
  8.         for(;;) {
  9.                 printf("input a integer please : ")     ;
  10.                 fgets(buf , 80 , stdin)                 ;
  11.                 if(sscanf(buf , "%d" , & n) == 1) break ;
  12.                 else printf("input error !\n")          ;
  13.         }
  14.         printf("n = %d\n" , n)                          ;
  15. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-4-7 10:20:00 | 显示全部楼层

这位朋友,可以讲一下吗。。。
那个为什么用fgets()
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-4-7 10:31:10 | 显示全部楼层

十分感谢,我明白了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-4 14:48

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表