gpt4 book ai didi

C 程序无法读取 .txt 文件中的用户名和密码

转载 作者:行者123 更新时间:2023-11-30 15:02:43 24 4
gpt4 key购买 nike

对于我的代码,我需要创建一个包含用户名(名字)和密码(姓氏)的 .txt 文件。我的代码需要读取该文件。如果我输入了正确的用户名和密码,它会让我登录。如果不正确,它不会让我登录。到目前为止,在我的 name.txt 文件(包含我的用户名和密码的文件)中,我有

Lebron James
Joe Smith
Nick Davis

如果我的用户名和密码正确,我希望它允许我登录。当我运行我的代码时,我收到一个中断错误。我似乎无法在我的代码算法中找到问题。

//This is my code: 
#include <stdio.h>
#include <stdlib.h>

struct account {
char id[20];
char password[20];
};

static struct account accounts[10];

void read_file(struct account accounts[])
{
FILE *fp;
int i = 0; // count how many lines are in the file
int c;
fp = fopen("names.txt", "r");
while (!feof(fp)) {
c = fgetc(fp);
if (c == '\n')
++i;
}
int j = 0;
// read each line and put into accounts
while (j != i - 1) {
fscanf(fp, "%s %s", accounts[j].id, accounts[j].password);
++j;
}
}

int main()
{
read_file(accounts);
// check if it works or not
printf("%s, %s, %s, %s\n",
accounts[0].id, accounts[0].password,
accounts[1].id, accounts[1].password);
return 0;
}

最佳答案

您不需要提前知道行数。只需使用 fscanf() 读取名称和密码对,直到返回 EOF

while (fscanf(fp, "%s %s", accounts[j].id, accounts[j].password) != EOF) {
++j;
}

另外,不要使用feof()。它通常不会按照您期望的方式工作。 feof() 仅在程序尝试读取文件但失败后才返回真值。也就是说,它不会阻止循环尝试读取文件末尾之后的内容。

关于C 程序无法读取 .txt 文件中的用户名和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40951503/

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