#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/