比较c ++中数组的元素

时间:2014-02-14 08:44:14

标签: c++ arrays comparison

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

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";
    }
}

2 个答案:

答案 0 :(得分:1)

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

ctr = getch();

里面的..

PLUS :指令

inputPin[ctr];

没有效果!

您已添加:

inputPin[cnt] = putchar(ctr);

<强> SUGGESTION
只是为了使代码清晰,将“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 */
}

答案 1 :(得分:0)

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";
            }
    }
相关问题