You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言Switch循环异常:执行Case1/2后无法再次进入对应分支

问题原因与解决方法:重复进入添加分支无响应

我一眼就看到了问题所在——你用来控制添加条目的变量another没有在每次进入添加分支时重置!

具体原因分析

你在main函数开头把another初始化为'y',第一次执行case1或case2时,当你输入'n'结束添加,another的值就变成了'n'。之后再次进入case1或case2时,while(another=='y')这个循环条件直接不成立,代码直接跳过了所有添加逻辑,看起来就像“无响应”一样。而其他分支(比如查看客户/交易信息)不依赖这个变量,所以能正常工作。

另外还有个小细节:你用.exe作为数据文件的后缀,这很容易和程序的可执行文件搞混,建议改成.dat这类更合适的后缀。

解决方法

只需要在每次进入case1和case2时,重新把another设置为'y',确保循环能正常启动。下面是修改后的代码,关键修改处我标了注释:

#include <stdio.h>
#include <stdlib.h>
#define N 2
struct customer {
 int accno ;
 char name[30] ;
 float balance ;
}e,m;
struct trans {
 int accno;
 char trans_type ;
 float amount ;
}e2,m1;
int main() {
 int k,i,p;
 char another='y',n;
 FILE *fp,*fr,*tp;

 while(1){
 printf("\t\tCustomer Transactions:\n");
 printf("\t\t*********************\n\n\n");
 printf("\t1: Add customer information:\n\n");
 printf("\t2: Add transaction information:\n\n");
 printf("\t3: List customer information:\n\n");
 printf("\t4: List transaction information:\n\n");
 printf("\t5: Perform transaction:\n\n");
 printf("\t0: Exit:\n\n\n");
 printf("your choice ");
 scanf("%d",&p);
 switch (p){
 case 1:
 fp=fopen("customer.dat","wb");  // 把后缀改成.dat,避免和可执行文件混淆
 another = 'y';  // 重置another为'y',确保循环能启动
 while(another=='y') {
 printf("\nEnter account number,Enter name,Enter balance");
 scanf("%d %s %f",&e.accno,&e.name,&e.balance);
 fwrite(&e,sizeof(e),1,fp);
 printf("Enter another y/n?");
 scanf(" %c",&another);
 }
 fclose(fp);
 break;
 case 2:
 fr=fopen("transaction.dat","wb");  // 同样修改后缀
 another = 'y';  // 重置another为'y'
 while(another=='y'){
 printf("\nEnter account number,Enter transaction type(w/d),Enter Amount");
 scanf("%d %c %f",&e2.accno,&e2.trans_type,&e2.amount);
 fwrite(&e2,sizeof(e2),1,fr);
 printf("\n\nEnter another y/n?");
 scanf(" %c",&another);
 }
 fclose(fr);
 break;
 case 3:
 fp=fopen("customer.dat","rb");
 printf("all account holders are\n\n");
 while(fread(&e,sizeof(e),1,fp)==1){
 printf("%d %s %f\n\n",e.accno,e.name,e.balance);
 }
 fclose(fp);
 break;
 case 4:
 fr=fopen("transaction.dat","rb");
 printf("\n\nEnter account number\n\n");
 scanf("%d",&m1.accno);
 while(fread(&e2,sizeof(e2),1,fr)==1){
 // 这里加个判断,只显示当前输入账号的交易记录
 if(e2.accno == m1.accno) {
 printf("%d %c %f\n\n",e2.accno,e2.trans_type,e2.amount);
 }
 }
 fclose(fr);
 break;
 case 0:
 exit(1);
 }
 }
 return 0;
}

额外优化建议

case4里你原本读入了账号但没用来过滤交易记录,我在代码里加了个判断逻辑,这样就能只显示对应账号的交易了,如果你不需要这个功能可以直接删掉。

内容的提问来源于stack exchange,提问作者Kanishk Tanwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:41:35