在 C++ 中比较数组的元素

comparing elements of an array in c++

本文关键字:元素 数组 比较 C++      更新时间:2023-10-16

我们有一个模拟ATM功能的项目。 用户必须输入 PIN 码,它将被星号屏蔽。 输入 PIN 码必须等于存储在数组中的默认 PIN 码。我的程序可以用星号屏蔽输入密码,唯一的问题是即使输入密码与默认密码相同,它仍然输出不正确。一定有什么问题?这是我的代码:

void checkPword()
{
    char defaultPin[4] = "1234";
    char inputPin[4] = "";
    clrscr();
    for (int cnt = 0; cnt <= 3; cnt++)
    {
        cout << "*";
        inputPin[ctr];
    }
    if (defaultPin[0] == inputPin[0] && defaultPin[1] == inputPin[1]
        && defaultPin[2] == inputPin[2] && defaultPin[3] == inputPin[3])
    {
        clrscr();
        cout << "pincode is correct"; 
    }
    else
    {
        clrscr();
        cout << "pincode is incorrect";
    }
}

也许你必须将getch()分配给ctr?

ctr = getch();

里面为..

加号:说明

inputPin[ctr];

没有效果!

您已添加:

inputPin[cnt] = putchar(ctr);

建议
为了使代码清晰,请将"CNT"替换为"i"。

溶液

char defaultPin[4]="1234";
char input[4] = "";
char currentChar;
bool pinFail = false;
for(int i=0; i != 3; i++) {
   currentChar = getchar();
   input[i] = currentChar;
   /* In this way you have only 3 if-control, not 3*4 as in your program */
   if(currentChar != defaultPin[i]) {
     pinFail = true;
   }
}
if(pinFail) {
   /* do something (print error?) */
} else {
   /* coutinue with your application */
}
void checkPword()
    {
    char defaultPin[4]={1,2,3,4};
    char inputPin[4]="";
    clrscr();
    for(int cnt=0;cnt<=3;cnt++)
        {
           inputPin[cnt] = getch();
           cout<<"*";
        }
        if ((defaultPin[0]==inputPin[0])&&(defaultPin[1]==inputPin[1])&&(defaultPin[2]==inputPin[2])&&(defaultPin[3]==inputPin[3]))
            {
             clrscr();
             cout<<"pincode is correct"; 
            }
        else
            {
             clrscr();
             cout<<"pincode is incorrect";
            }
    }