【问题标题】:Program Crash when Reading from File从文件读取时程序崩溃
【发布时间】:2014-09-05 21:53:31
【问题描述】:
#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);
}

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

文件格式为

first last

first last

first last

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

【问题讨论】:

  • firstname 只为 9 个字符加上终止的 NULL 字符分配足够的空间。 firstname + 空格 + lastname 有没有可能比这更长?
  • 今天好像很多人都有相同的作业:stackoverflow.com/questions/25691729/…

标签: c file-io


【解决方案1】:

我看到的问题:

问题 1

行:

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

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

要解决该问题,请指定要读取的最大字符数。另外,从类型的角度来看,使用firstname 而不是&amp;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);

解决这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    相关资源
    最近更新 更多