gpt4 book ai didi

c - 在C中,如何存储长字符串(例如密码)

转载 作者:行者123 更新时间:2023-11-30 15:26:57 25 4
gpt4 key购买 nike

嗯,我有这个程序来检查密码。如果我将第二个数组(即 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;
}

最佳答案

虽然您 可以 将 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);

关于c - 在C中,如何存储长字符串(例如密码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27250767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com