2014-02-14 114 views
1

我们有一个模拟atm函数的项目。用户必须输入密码并用星号标记。输入pincode必须等于存储在数组中的默认pincode。我的程序可以用星号屏蔽输入pincode,唯一的问题是即使输入pincode与默认pincode相同,它仍然输出不正确。问题是什么?这里是我的代码:比较C++中数组的元素

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

字串' “1234”'实际上包含了五个* *字符。你不能忘记终止''\ 0''。这意味着你正在写入'defaultPin'数组的范围之外。 –

+2

另外,声明'inputPin [ctr];'应该做什么? –

+0

您是否尝试添加一个断点来查看程序没有达到您期望的确切点?调试技巧不仅适用于此程序,还适用于您编写的未来程序。 –

回答

1

也许你必须指定getch()到ctr?

ctr = getch(); 

里面的..

PLUS:指令

inputPin[ctr]; 

没有效果!

您有加:

inputPin[cnt] = putchar(ctr); 

SUGGESTION
只是为了让代码清晰,用 “I” 替换 “CNT”。

SOLUTION

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