使用 if 和 else if 的简单 ATM 机的 c 程序

标签 c visual-c++

我无法弄清楚错误在哪里。当我尝试运行该程序时,它不会通过选择,而是在要求选择后直接进入程序末尾。并且,它还在 Visual C++ 编译器的“显示生成的输出”中给出了一些警告。有人可以帮我解决这个问题吗?

     #include <stdio.h>
     int main ()
     {
     int card_number, choice, withdraw, deposit;
     float amount = 3000.00, new_amount = 0;
     char password;
     printf("Enter the card number: ");
     scanf("%d", &card_number);
     printf("Enter the Password: ");
     scanf(" %c", &password);
     printf("\n\n");
     printf("\n\t***********************************");
     printf("\n\t*           MENU                  *");
     printf("\n\t*     1. Check Balance            *");
     printf("\n\t*     2. Withdraw                 *");
     printf("\n\t*     3. Deposit                  *");
     printf("\n\t*     4. Exit                     *");
     printf("\n\t*                                 *");
     printf("\n\t***********************************");
     printf("\n\n");
     printf("Enter your choice: ");
     scanf("%d", &choice);

     if (choice == 1)
       {
      printf("Current balance on your account: %f\n", amount);
       }
     else if (choice == 2)
      {
    printf("Enter the amount you want to withdraw: ");
    scanf("%d", &withdraw);

    if (withdraw > amount)
      {
        printf("You don't have sufficient balance");
      }
    else
      {
        new_amount = amount - withdraw;
        printf("Current balance on your account: %f\n", new_amount);
      }
}

else if (choice == 3)
{
    printf("Enter the amount you want to deposit: ");
    scanf("%d", &deposit);
    amount = amount + deposit;
    printf("Current balance on your account: %d\n", amount);
}
else if (choice == 4)
{
    printf("Thank you for using our service\n\n");
}

return 0;
    }

最佳答案

大概您希望密码的长度超过一个字符,因此您需要一个“字符串”而不是单个 char。不幸的是,C 没有字符串类型,但它有足够好的 char 数组。与其通过 scanf("%c",&password); 请求字符,不如通过 scanf("%s",&password); 请求“字符串”。 但是password必须定义为一个长度足以保存密码的char数组。[1]

这导致您的程序“跳到末尾”的原因是因为 %c 只读取输入的一个字符。您可能输入了几个字符。稍后在程序中,您尝试通过 %d 读取 int,它不能使用密码的非数字,因此 scanf() 调用失败,但您没有检查这些调用的返回值,因此您的代码不知道这些失败。


[1] 实际上,password 必须足够长以容纳用户决定输入的任何内容。实际上,您应该研究使用格式宽度(例如 %20s)来防止数组溢出,这是一个严重的安全漏洞。但由于这是一项家庭作业,我们假设这些细节目前并不重要。

关于使用 if 和 else if 的简单 ATM 机的 c 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19442991/

相关文章:

c++ - MSVC 上的双字节编码 (std::codecvt):无法识别前导字节

c - OpenCV cvCaptureFromCAM 返回 NULL

c - Linux 上的 strdup 使用哪个宏?

c - 当 realloc 缩小分配的 block 时,释放的内存在哪里?

c++ - 文件流问题

visual-c++ - 将 MFC CString 转换为整数

c - 使用指向c中指针变量的指针将二维数组传递给函数

c - 带互斥量的 Linux 线程

c++ - 具有协变返回类型和模板类参数的虚拟继承,vs2013 中的 LINK 错误

mfc - DoModal() 在第一行断言