c - 字符串数组与用户字符串比较给出访问错误

标签 c arrays file

我正在尝试构建一个程序,该程序将从文件中获取登录详细信息(用户名和密码)的列表,并允许您选择输入与批准登录并给出结果。在我的 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);
}

最佳答案

@安东尼戈登

  1. 字符串 usrname 和 userPassword 很可能没有以 '\0'(空终止符)结尾 a) 因为 scanf() 可能会尝试填充比 usrname 可以捕获的更多的字符 b) for 循环只需迭代 5 次,以便将 userPassword[5] 显式设置为“\0”。 (如果期望使用 6 个字符长的用户名和密码,则将数组的长度从 6 更改为 7 并确保数组 [6] 填充为 '\0')(记住 'C' 数组下标为 0 ..(arraysize-1))

  2. 另外,一旦用户名和密码匹配,跳出循环。

关于c - 字符串数组与用户字符串比较给出访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36020557/

相关文章:

node.js - nodejs oracledb 选择数据 WHERE IN 值数组

javascript - 为什么这个函数返回 "undefined"而不是数组?

python - 打印一个值之间带有制表符的元组

c - 在 C 中解析程序参数时有什么好的做法

c - 结构体作为外部函数 C 的参数

c - 如何从C中的省略号获取不同类型的参数

python - NumPy:当类似数组的类中 __array_ufunc__=None 时,某些运算符不起作用

php - 使用 PHP 将文本 append 到文本文档中的行

Python 按给定顺序将多个文件 append 到一个大文件

C和 Bison : pointers to struct in %union definition