【发布时间】:2014-12-02 13:33:23
【问题描述】:
嗯,我有这个程序检查密码。如果我将第二个数组(即 for 循环)设置为 8 位,它工作正常。但是一旦 pw 需要超过 8 位数字,整个事情就会出错(因为 for 循环需要 10 位数字)。
我认为将第一个数组声明为 MAXLINE long 会起作用,但它似乎并没有解决问题。
/* IMPORT ---------------------- */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* CONST------------------ */
#define MAXDIGIT 10000
/* VARIABLES (global) ---------- */
/* MAIN--------------- */
int main()
{
/* VARIABLES (local) --------- */
/* VARIABLES (local) --------- */
// ENTERED PW:
char EnterCode[MAXDIGIT];
int i;
// REAL PW:
char arr[MAXDIGIT] = "123456789"; //"YKJ98LGDDF";
int j;
printf("PW: "); // for testing
for (j = 0 ; j < 8; ++j){
printf("%c", arr[j]);
}
/* Intro --------------------- */
printf("\nPlease enter code of authorization: ");
for(i = 0; i < 10; ++i){
scanf("%c", &EnterCode[i]);
printf("%c", EnterCode[i]); // test 1
}
if (strcmp(EnterCode,arr) == 0){
printf("\nAccess authorized.\n");
}else{
printf("\nAccess denied!\n");
}
system("PAUSE");
return 0;
}
【问题讨论】:
-
您永远不会将
'\0'字符插入EnterCode。strcmp要求字符串正确终止。 -
读取输入直到遇到换行符...
-
EnterCode很可能不是空终止 -
另外,不要将 10000 个字符放在堆栈上,使用堆(即 malloc)
标签: c arrays string compare c-strings