我正在尝试构建一个程序,该程序将从文件中获取登录详细信息(用户名和密码)的列表
,并允许您选择输入与批准登录并给出结果。在我的 strcmp
中,我收到了 access violation error 0xC0000005
。
#include <stdio.h>
#include <conio.h>
#include<stdlib.h>
FILE *fptr;
void main();
void openFile();
void closeFile();
char approvedUsrnames[3][6];
char approvedPassword[3][6];
void main()
{
char userPassword[6], usrname[6], inputChar, fileString[6];
int i;
openFile();
int numofLogins= 3;
if (fptr != NULL)
{
printf("\nReading file with scanf\n");
while (!feof(fptr))
{
for (i = 0; i < 3; i++) {
fgets(approvedUsrnames[i], 6, fptr);
fgets(approvedPassword[i], 6, fptr);
}
}
closeFile();
}
printf("Enter User name: ");
scanf("%s",usrname);
printf("Enter the password <any 6 characters>: ");
for (i = 0; i<6; i++)
{
inputChar = _getch();
userPassword[i] = inputChar;
inputChar = '*';
printf("%c", inputChar);
}//obfuscate the input to the user
/*If you want to know what you have entered as password, to be removed*/
printf("\nYour password is %s:", userPassword);
for (i = 1; i < 3; i++) {
printf("\Username is good %s\n", approvedUsrnames[i]);
if (strcmp(approvedUsrnames[i], usrname == 0)){
printf("\Username is good\n");
if (strcmp(userPassword, approvedPassword[i]) == 0) {
printf("\nPassword is good\n");
}//end nested if
else {
printf("\nPassword is not match\n");
}
}//end if
}//end for
_getch();
}
void openFile()
{
fptr = fopen("approvedLogins.dat", "r");
if (fptr == NULL)
{
printf("Error opening file ! \n");
}
else {
printf("Login file read successfully ! \n");
}
}
void closeFile()
{
fclose(fptr);
}
最佳答案
@安东尼戈登
字符串 usrname 和 userPassword 很可能没有以 '\0'(空终止符)结尾 a) 因为 scanf() 可能会尝试填充比 usrname 可以捕获的更多的字符 b) for 循环只需迭代 5 次,以便将 userPassword[5] 显式设置为“\0”。 (如果期望使用 6 个字符长的用户名和密码,则将数组的长度从 6 更改为 7 并确保数组 [6] 填充为 '\0')(记住 'C' 数组下标为 0 ..(arraysize-1))
另外,一旦用户名和密码匹配,跳出循环。
关于c - 字符串数组与用户字符串比较给出访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36020557/