【发布时间】:2016-07-01 10:34:09
【问题描述】:
我正在尝试构建一个程序,该程序将从文件中获取登录详细信息(用户名和密码)的list,并允许您选择输入用户名和密码,并将其与批准的登录名和结果进行比较给出。在我的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);
}
【问题讨论】:
-
userPassword不是 NUL 终止的。 -
@kaylum 你能解释一下你的意思以及我将如何解决它吗?
-
您正在使用
userPassword作为字符串(例如在strcmp中)。 C 中的字符串必须有一个\0字符作为数组中的最后一个字节。您的userPassword有 6 个字节的非 NUL 数据,因此不是有效的 C 字符串。一种解决方法是为 NUL 分配额外空间并显式初始化变量:char userPassword[7]="";` -
添加一个字符并初始化字符串会在 strcmp 上产生相同的错误
-
好吧,你打错了:
strcmp(approvedUsrnames[i], usrname == 0)。==0错误地位于strcmp中。