【问题标题】:In C, how can a store long strings (example passwords)在 C 中,如何存储长字符串(示例密码)
【发布时间】: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' 字符插入EnterCodestrcmp 要求字符串正确终止。
  • 读取输入直到遇到换行符...
  • EnterCode 很可能不是空终止
  • 另外,不要将 10000 个字符放在堆栈上,使用堆(即 malloc)

标签: c arrays string compare c-strings


【解决方案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);

【讨论】:

  • 我会使用"%19s" 来表示scanf 格式控制字符串。
  • 注意:使用"%19s" 防止使用空格、制表符等作为密码的一部分。此外,如果用户输入“123 456”,则“123”将是密码,而“456”将保留在stdin 中。使用"%19[^\n]%*c"fgets() 可能是更好的方法。
  • @chux - 首先感谢!这是一个有用的建议。但是,我在整个页面上没有看到来自 OP 的单一响应(除了问题之外),当感觉对某人的问题几乎没有或没有真正的兴趣时,回答(或改进对)某人的问题有点不那么有趣提问者的回答。你会同意吗? :)
  • @ryyker 对 OP 的看法是正确的——还有其他贡献者,比如你自己,通常会提供一些绝妙的见解。
【解决方案2】:

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

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

【讨论】:

  • "123456789" 表示给我一个以空字符结尾的字符串。 "123456789\0" 表示给我一个带有 2 个空终止符的字符串,没有明显的原因。
【解决方案3】:

替换

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

scanf("%s", EnterCode);

然后再试一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2012-10-25
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多