使用goto语句创建循环失效:程序仅单次迭代后终止的技术问询
问题原因分析
你的程序仅执行一次循环就终止,核心问题是输入缓冲区残留的换行符被scanf("%c", &item)读取:
- 当你输入
M/m/H/h并按下回车后,输入缓冲区里会留下目标字符加换行符\n - 第一次
scanf("%c", &item)读取了目标字符,但换行符留在缓冲区 - 第二次循环时,
scanf("%c", &item)直接读取了缓冲区里的\n,这个字符不属于M/H/m/h,触发default分支的goto stop,导致程序终止
修复方案
在读取字符的scanf格式串前加一个空格,让它自动跳过所有空白字符(包括换行符、空格、制表符):
scanf(" %c", &item);
另外你代码里的提示文本有拼写错误:handllom应该是handloom,建议修正。
修改后的完整代码
// a clothes showroom has announced a discount on mill cloth and handloom items , wap using switch and if stmts to compute the net amount to be paid by customer #include<stdio.h> float netmillcloth(float a) { if(a>300) a-=0.10*a; else if(a>200) a-=0.075*a; else if(a>100) a-=0.05*a; return a; } float nethandloom(float a) { if(a>300) a-=0.15*a; else if(a>200) a-=0.10*a; else if(a>100) a-=0.075*a; else a-=0.05*a; return a; } int main() { char item; float purchase_amt, net; // net is amount to be paid after discount input: printf("Enter the type of item bought\nM for millcloth\nH for handloom items\nother key to end program\n"); scanf(" %c", &item); // 加空格跳过空白字符 switch(item) { case 'M': case 'm': printf("\nenter purchase amount:"); scanf("%f", &purchase_amt); net=netmillcloth(purchase_amt); break; case 'H': case 'h': printf("\nenter purchase amount:"); scanf("%f", &purchase_amt); net=nethandloom(purchase_amt); break; default: goto stop; } printf("\nThe final amount to be paid is:%f\n\n", net); goto input; stop: printf("\nEnd of program"); }
补充说明
- 用
goto实现循环的逻辑本身是成立的,只要处理好输入缓冲区问题就能正常循环 - 除了加空格的方式,也可以在读取金额后用
getchar()清理缓冲区,但加空格的方式更简洁通用
内容的提问来源于stack exchange,提问作者Rishabh
相关产品推荐
相关产品推荐

