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

如何让C++程序在3次PIN密码输入错误后自动终止运行

问题修复方案

核心错误原因

  • 循环内的分支逻辑完全错位,3次输入失败的终止判断写在了错误的分支下,且使用了赋值运算符=而非比较运算符==,导致终止逻辑永远不会触发
  • 没有在while循环退出后判断是否已经达到3次错误上限,只要循环退出就会直接进入后续的面积计算菜单

修复步骤

  1. 删除原循环内错误的else if ( attemptCount = 0 )分支逻辑
  2. 在while循环结束后新增判断:如果attemptCount == 3,说明3次全部输入错误,输出提示后直接return 0终止程序

修正后完整代码

#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string pin;
    int attemptCount = 0;

    while ( attemptCount < 3 )
    {
        cout << "Enter pin: " << endl;
        cin >> pin;

        if ( pin != "1234")
        {
            cout << "Pin is incorrect." << "\n" << endl;
            attemptCount++;
        }
        else
        {
            cout << "Access granted." << endl;
            break;
        }
    }

    // 新增3次错误判断逻辑
    if (attemptCount == 3)
    {
        cout << "3 pins were unsuccessful.";
        return 0;
    }

    int a, b, c;
    char choice;
    cout<<"\n\n---Area of a polygon---\n[A] Triangle\n[B] Square\n[C] Rectangle\n[D] Exit \n";
    cout<<"Enter choice: \n";
    cin>>choice;
   
    switch(choice){
        case 'a':
        case 'A':
            int square_area, square_side;
            float base, height, area1;
            cout << "\nEnter length of base and height of Triangle: ";
            cin >> base >> height;
            area1 = (base * height) / 2;
            cout << "Area of Triangle: " << area1 << endl;
            break;
            
        case 'b':
        case 'B':
            cout<<"\nEnter the side of the square: ";
            cin >> square_side;
            square_area = square_side * square_side;
            cout << "Area of Square: " << square_area << endl;
            break;
            
        case 'c':
        case 'C':
            int length, width, area;
            cout << "\nEnter the Length of Rectangle : ";
            cin>>length;
            cout << "\nEnter the Width of Rectangle : ";
            cin>>width;
            area = length * width;
            cout << "\nArea of Rectangle : " << area;
            break;
   
        case 'd':
        case 'D':
            break;
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Edrick Paras

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:06:03