【问题标题】:C program compiles in xcode, but runs infinite loop in terminalC程序在xcode中编译,但在终端中运行无限循环
【发布时间】:2016-12-09 04:51:48
【问题描述】:

我一直在为系统编程课程编写一个小组程序,该课程将运行银行某人会使用的功能。这些功能包括添加银行客户、输出客户余额等。问题在于添加客户功能。

此函数将在终端和 Putty 中无限循环运行,但是当我在 XCode 中将其作为独立程序运行时,循环退出。我、我的小组成员和我们的教授忽略的程序有什么问题吗?

#include <stdio.h>
#include <string.h>
#include "./bank.h"

void add(FILE *fp)
{
    int i=0;
    char firstName[20];
    char lastName[20];
    float camount;
    int prompt;
    float samount;
    float mamount;
    fseek(fp,0,2);
do

{
   printf("\nEnter first name: ");
   scanf("%s", firstName);
   strcpy(bank[i].firstName, firstName);

   printf("\nEnter last name: ");
   scanf("%s",lastName);
   strcpy(bank[i].lastName, lastName);

   printf("\nEnter checking account balance: ");
   scanf("%f", &camount);
   bank[i].checking = camount;

   printf("\nEnter savings account balance: ");
   scanf("%f", &samount);
   bank[i].savings = samount;

   printf("\nEnter money market account balance: ");
   scanf("%f", &mamount);
   bank[i].moneyMarket = mamount;

   fwrite(&bank[i],1, sizeof(struct BankInfo),fp);
   i++;

   printf("Enter 1 to enter another name and 0 to quit: ");
   scanf("%d", &prompt);
   printf("%d\n", prompt);

   } while(prompt == 1);

   fclose(fp);
   return;
}

Makefile 执行后的输出截图:

旁注:这个函数确实写入了我们正在传递的文件,这很好,但我们仍然需要让它跳出循环。

编辑: main 函数的代码: #包括 #包括 #包括 #include "bank.h" #include "definitions.h"

int main()
{
FILE *fp;
int selection;
fp=fopen("bankInfo.dat","ab+");

selection=menu();

while(selection !=6)
{
switch(selection)
{
  case 1:
       add(fp);
       break;

       case 2:
          //  outputBalance(fp);
            break;
      case 3:
            delete(fp);
            break;
      case 4:
            update(fp);
            break;
    case 5:
         // display(fp);
            break;
    case 6:
            exit(0);
            break;
    default:
            printf("Invalid selection\n");
            break;
    }
}
fclose(fp);
return 0;
}

【问题讨论】:

  • 是否有其他调用 add 函数的东西在循环中?
  • 请显示你调用这个Add函数的代码。
  • 我刚刚将主要功能添加到我的问题中
  • selection 不要在 while(selection !=6){...} 内部更新

标签: c xcode macos terminal systems-programming


【解决方案1】:

您只分配一次选择。这应该可以解决您的问题:

while(true)
{
selection=menu();
switch(selection)
{
  case 1:
       add(fp);
       break;

       case 2:
          //  outputBalance(fp);
            break;
      case 3:
            delete(fp);
            break;
      case 4:
            update(fp);
            break;
    case 5:
         // display(fp);
            break;
    case 6:
            fclose(fp);
            exit(0);
            break;
    default:
            printf("Invalid selection\n");
            break;
    }
}
return 0;

【讨论】:

  • 谢谢!这让我们整天发疯!我们问了 3 位不同的教授,他们都搞不清楚。
  • @你当然是对的。实际上,循环条件中根本不需要检查选择值。
猜你喜欢
  • 1970-01-01
  • 2017-02-06
  • 2020-11-29
  • 2018-08-29
  • 2020-05-19
  • 2014-02-07
  • 1970-01-01
  • 2017-01-18
  • 2017-05-23
相关资源
最近更新 更多