首页 > 解决方案 > 我的 C 代码没有捕捉到“最终客户”结束

问题描述

我正在用 C 编写代码以从用户那里读取客户数据并在屏幕上打印客户数据,直到读取客户名称“最终客户”(即 first_name last_name)。

我认为包括 if 循环和 strcmp() 将捕获输入“最终客户”并防止打印客户记录。但是,当我运行它时,它并没有结束。这是我的主要功能:

#include <stdio.h>
#include <string.h>
struct account {
   struct
   {
      char lastName[10];
      char firstName[10];
   } names;
   int accountNum;
   double balance;
};
void nextCustomer(struct account *acct);
void printCustomer(struct account acct);
int main()
{
   struct account record;
   int flag = 0;

   do {
      nextCustomer(&record);
      if ((strcmp(record.names.firstName, "End") == 0) && //I thought this would be able to catch the End Customer//
          (strcmp(record.names.lastName, "Customer") == 0))
         flag = 1;
      if (flag != 1)
         printCustomer(record);
   } while (flag != 1);
}

这些是我分别读取客户数据和打印客户数据的两个功能:

void nextCustomer(struct account *acct)
{
    struct account {
       struct
       {
          char lastName[10];
          char firstName[10];
       } names;
       int accountNum;
       double balance;
    } record;
    printf("Enter names (firstName lastName): ");
        
    scanf("%s %s", (acct->names).firstName, (acct->names).lastName);
    printf("Enter account number: ");
    scanf("\n");
    scanf("%d", &acct->accountNum);
    printf("Enter balance: ");
    scanf("%lf", &acct->balance);
}
void  printCustomer(struct account acct)
{
    printf("Customer record: \n %s %s %d %.2lf\n", acct.names.firstName, acct.names.lastName, acct.accountNum, acct.balance);
}

谢谢!

标签: c

解决方案


您当前的代码将nextCustomer完全执行,直到完成对所有输入(姓名、帐号和余额)的扫描。只有在那之后,代码才会检查名字和姓氏。需要在扫描后立即检查名称,因此如果您获得“最终客户”,您可以提前退出。

检查此代码以获取解决方案:https ://onlinegdb.com/HJr_YS9Yw


推荐阅读