求C程序高手!!!

[复制链接]
查看11 | 回复5 | 2010-5-28 13:45:41 | 显示全部楼层 |阅读模式
我是个C程序的初学者,请教一下C程序高手下面一个问题:
#include
void main()
{
char a;
loop:printf("Please input the number:");
scanf("%c",&a);
if(a!='y') {printf("Input data error,please input again.\n");goto loop;}
else printf("Success!\n");
}
我本想输入除y以外的其他字母时会出现如下字样:
input data error,please input again.
please input the letter.
可却出现了以下结果:
input data error,please input again.
please input the letter.input data error,please input again.please input the letter.
Please input the number:
我想不通,求高人指点,让我可以得到原想结果。。感激不尽。。

回复

使用道具 举报

千问 | 2010-5-28 13:45:41 | 显示全部楼层
这个问题是这样的:scanf函数读取键盘缓冲区里的字符流,如果遇到空格,回车时就会截断字符流,把空格或者回车前的部分读到参数指定的地址(本例中是a)。假如你运行程序时,输入y以外的字符然后回车(注意这时键盘缓冲区里边有两个字符:'a','\n'),它就会先把这个字符付给a,会输出Input data error,please input again. 然后你重新开始loop,输出Please input the number: 然后它会把回车'\n'读到a里面,这时也是输出Input data error,please input again.这时候键盘缓冲区空了,就在输出Please input the number:并且等待键盘输入
回复

使用道具 举报

千问 | 2010-5-28 13:45:41 | 显示全部楼层
你的结果怎么会出现“please input the letter”让我想不通,你的程序中根本没这句啊?我改的你试试,因为我没装运行软件,所以只能你自己运行看看了。你原来的应该是顺序错了。#includevoid main(){char a;scanf("%c",&a);if(a!='y') {printf("I
回复

使用道具 举报

千问 | 2010-5-28 13:45:41 | 显示全部楼层
代码改一下就可以了。如下:char a;loop:printf("Please input the number:");scanf("%c",&a);fflush(stdin);if(a!='y') {
printf("Input data error,please input again.\n");
goto l
回复

使用道具 举报

千问 | 2010-5-28 13:45:41 | 显示全部楼层
应为你连续输入的字母都不是y,所以进入循环,输出please input the letter.input data error,please input again.please input the letter. Please input the number
回复

使用道具 举报

千问 | 2010-5-28 13:45:41 | 显示全部楼层
你是选择了从CD-ROM恢复光盘镜你,但是你没有完成就重启了,自然就~~嘿嘿~~~试试把光盘重新放入光驱,再让它启动一次试试
回复

使用道具 举报

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

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行