c - 从文件读取时程序崩溃

标签 c file-io

#include <stdio.h>
#include <string.h>

struct candidate
{
char candidateName[20];
int votes;
};



Initialize()
{
    char firstname[10];
    char lastname[10];
    FILE* ifp;
    int i;
    struct candidate electionCandidates[7];
    ifp = fopen("elections.txt", "r");
    for (i = 0; i<7; i++)
    {
        strcpy(electionCandidates[i].candidateName, "aaaaa");
        electionCandidates[i].votes = 0;
    }
    for (i=0; i<7; i++)
    {
        memset(&firstname[0], 0, sizeof(firstname));
        memset(&lastname[0], 0, sizeof(firstname));

        fscanf(ifp, "%s %s", &firstname, &lastname);
        strcat (firstname, " ");
        strcat (firstname, lastname);
        strcpy (electionCandidates[i].candidateName, firstname);
        printf("%s", electionCandidates[i].candidateName);
    }


}

int main()
{
    Initialize();
    return(0);
}

上面的代码应该从文件中读取名字和姓氏,并将它们添加到结构的candidateName部分。当我运行这个程序时,它分配并打印开头的名字和姓氏,但随后立即崩溃。

该文件的格式为

first last

first last

first last

等等

我觉得这可能与不阅读下一行有关,但我不知道该怎么做。任何帮助将不胜感激。

最佳答案

我看到的问题:

问题1

行:

fscanf(ifp, "%s %s", &firstname, &lastname);

如果输入文件中的名字和/或姓氏超过 9 个字符,就会出现问题。

要解决该问题,请指定要读取的最大字符数。另外,从类型的角度来看,请使用 firstname 而不是 &firstname

fscanf(ifp, "%9s %9s", firstname, lastname);

问题2

线条

strcat (firstname, " ");
strcat (firstname, lastname);

如果 firstname 的长度 + lastname 的长度大于 8,就会出现问题。

您可以使用:

strcpy (electionCandidates[i].candidateName, firstname);
strcat (electionCandidates[i].candidateName, " ");
strcat (electionCandidates[i].candidateName, lastname);

解决这个问题。

关于c - 从文件读取时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25694513/

相关文章:

c++ - 计数排序 我的输入是1,4,3,1 但输出是垃圾值,1,1,3 输入不正确

php - 在 PHP7 扩展中创建循环对象时发生内存泄漏

c - 确保父进程在子进程之前终止

C 程序将文件 io 传递给函数

c - 另一个令人头疼的winapi文件权限C。为什么我的方法不起作用?

ruby - 获取实例化类 ruby​​ 的文件目录

c - 在结构初始化中定义常量变量

python - 如何将 Beautiful soup 输出数据保存到文本文件中?

c - 'file data' 和 'file size' 是一起还是单独提交到磁盘

c - 两个不同函数指针的 typedef 有效吗?