gpt4 book ai didi

c - 开关环和外壳

转载 作者:行者123 更新时间:2023-11-30 20:59:07 24 4
gpt4 key购买 nike

#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;
//fp=fopen("customer.exe","rb");
//fr=fopen("transaction.exe","wb");
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.exe","wb");
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.exe","wb");
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.exe","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.exe","rb");
printf("\n\nEnter account number\n\n");
scanf("%d",&m1.accno);
while(fread(&e2,sizeof(e2),1,fr)==1){
printf("%d %c %f\n\n",e2.accno,e2.trans_type,e2.amount);
}
fclose(fr);
break;

case 0:
exit(1);

}
}
return 0;
}

嘿伙计们,所以我正在解决这个问题,但我陷入了 switch 循环中所以发生的情况是,只有在编译和运行时我才能自由选择任何情况,但是如果我在任何情况下,尤其是 1 或 2,我就无法返回到 1 或 2。

例如,假设我输入 p 作为 1 宾果,我处于情况 1,但现在在情况 1 执行后,如果我现在输入 2,什么也没有发生。陷入 while 循环,但疯狂的是,我仍然可以自由选择其他情况。(除了 1/2)

最佳答案

当您退出case-1时,您输入的another'n'。然后,在再次考虑开关盒之前,您永远不会重置它。这就是问题所在。

while(1) block 内 - 在开头进行赋值 another = 'y'。这基本上将使两个 while 循环的条件为 true。

    while(1){
...

another = 'y'; <----
scanf("%d",&p);
switch (p){

case 1:
fp=fopen("customer.exe","wb");
while(another=='y')
{

这将使您的代码进入 case-1case-2 中的 while block 。

<小时/>
  • 除了所有这些之外,一般建议:检查所使用函数的返回值 - 例如 scanffopen 等。这将使您避免错误由于这些功能失效而可能发生的情况。

  • 并在启用警告的情况下编译代码。 gcc -Wall -Werror progname.c.

  • 以字符串作为输入时,应限制scanf的输入。例如,建议使用(如您所知,name 中有 30 个字符,包括 \0)。

    if( scanf("%29s",e.name) != 1){
    fprintf(stderr,"Error in input using scanf\n");
    exit(1);
    }

关于c - 开关环和外壳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com