一个关于scanf的问题,在线求救

python与大数据分析
博客专家认证
2003-07-09 03:04:05
Menu();
scanf("%d",&choice);
while(choice!=3)
{
switch(choice)
{
case 1:
printf("\nPlease input a pushed char:\n");
scanf("%c",&value);
Push(&startPtr,value);
PrintStack(startPtr);
break;
case 2:
if (IsEmpty(startPtr))
printf("\nThe Stack is Null\n");
else
printf("\nThe Poped char is /'%c/'\n",Pop(&startPtr));
PrintStack(startPtr);
break;
default:
printf("\nYou choose the error choice.\n");
break;
}
Menu();
scanf("%d",&choice);
}
看起来好像没问题
就是一个菜单,输入菜单选项(数字)后,就如相应功能
如果为1,输入一个字符,接受、处理后再次循环
但是实际运行中,总是直接显示Please input a pushed char,无法输入字符
这类问题c语言中经常碰到,为什么
...全文
60 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
bigtea 2003-07-09
  • 打赏
  • 举报
回复
同意stukov2002(卡拉是头猪) 对scanf()的看法,初学者常遇到此问题,一般是因为缓冲区中存有内容,被scanf()读了出来,认为是你的输入。如果必须用scanf(),解决方法有多种,
(1)在前面加getchar(),一般是把上次输入的回车符吸收。
(2)fflush(stdin),我用的有时候有效。
(3)加一个
char tmp;
scanf("%c",tmp);
x=tmp; 加中间变量来接收。
蝎子i软件 2003-07-09
  • 打赏
  • 举报
回复
这是一个很常见的问题。

其原因是在一个scanf(...)语句之后,有一个scanf("%c",pc)语句;//char *pc;
由于一般输入的习惯是在输入完成时回车,
而第一个scanf(...)语句并不读取回车符,
这样回车符就被scanf("%c", pc)语句读了。

最基本的解决办法是:
在上面提到的那种情况下,
在第一个scanf(...)语句之后添加一个scanf("%c", &tc)//char tc;
把回车符读掉。

例如:在楼主的程序中,
在scanf("%d",&choice);
加一句scanf("%c", &tc);
就可以解决问题了。
zteliubin 2003-07-09
  • 打赏
  • 举报
回复
试试每次fflush(stdin);//估计和这个有关
idontlikenickname 2003-07-09
  • 打赏
  • 举报
回复


scanf()函数比较灵活难用,如果只是进行菜单选择建议你使用getch()/getche()函数~
程序改为:

choice = getche(); // scanf("%d",&choice);
while(choice!='3')
{
switch(choice)
{
case '1':
printf("\nPlease input a pushed char:\n");
value = getche(); // scanf("%c",&value);
Push(&startPtr,value);
PrintStack(startPtr);
break;
case '2':
if (IsEmpty(startPtr))
printf("\nThe Stack is Null\n");
else
printf("\nThe Poped char is /'%c/'\n",Pop(&startPtr));
PrintStack(startPtr);
break;
default:
printf("\nYou choose the error choice.\n");
break;
}
Menu();
choice = getch(); // scanf("%d",&choice);
}

69,382

社区成员

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

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