2014-12-02 24 views
0

嗯,我有这个程序检查密码。如果我将第二个数组(即for循环)设置为8位数,它工作正常。但是一旦pw需要超过8位数字,整个事情就会出错(因为for循环会持续10位数字)。在C中,一个商店如何长字符串(例如密码)

我认为声明第一个数组是长时间MAXLINE会工作,但它似乎并没有解决问题。

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

你永远不会在'EnterCode'中插入''\ 0''字符。 'strcmp'要求字符串被正确终止。 – user694733 2014-12-02 13:41:21

+1

读取输入,直到遇到新行字符... – Lundin 2014-12-02 13:41:48

+0

'EnterCode'最有可能**不是** null **终止 – 2014-12-02 13:42:04

回答

0

在C语言字符串中以'\ 0'结尾。

因此,您的密码应该是“123456789”,并在输入“EnterCode” 后设置EnterCode [10] ='\ 0'(在您的代码中)。

+1

'“123456789”'表示给我一个以null结尾的字符串。 ''123456789 \ 0“'表示给我一个有2个空终端的字符串,没有明显的原因。 – Lundin 2014-12-02 13:45:47

+0

谢谢,修正 – KrK 2014-12-02 13:59:16

1

虽然你可以在回路放scanf函数,你不需要做,在你的应用程序:

如果输入的密码会在字符串中被捕获,简单地声明合理长度的字符串,用它来读取用户输入一个电话:

char EnterCode[20];//20 is just for illustration, pick any reasonable length for your application 

printf("enter your passcode:\n"); 
scanf("%19s", EnterCode); //limit characters read to 19 (leaving room for terminating NULL) 

对于一个超长的口令代码
而不是在栈上创建存储:

#define MAXDIGIT 10000 
char EnterCode[MAXDIGIT];//uses a large block of memory from a limited source 

将它放在堆:

char *EnterCode = {0}; 
EnterCode = malloc(MAXDIGIT); //also uses a large block of memory, but from a much much larger source 

当你使用EnterCode完成,释放内存:

free(EnterCode); 
+1

我会用''%19s''作为'scanf'格式的控制字符串。 – 2014-12-02 14:01:06

+0

@BasileStarynkevitch - 谢谢,完成。 – ryyker 2014-12-02 14:03:14

+1

注意:使用'“%19s”'可以防止使用空格,制表符等作为密码的一部分。此外,如果用户输入“123 456”,则“123”将是密码,“456”将保留在“stdin”中。使用“%19 [^ \ n]%* c”'或'fgets( )'可能是更好的方法 – chux 2014-12-03 17:35:31

0

更换

for(i = 0; i < 10; ++i){ 
    scanf("%c", &EnterCode[i]); 
    printf("%c", EnterCode[i]); // test 1 
} 

scanf("%s", EnterCode); 

,然后再试一次。

相关问题