0
#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
格式等
我覺得這可能是與它不打算讀取下一行,但我不知道該怎麼辦所以。任何幫助將不勝感激。
'firstname'只爲9個字符和終止空字符分配足夠的空間。 'firstname' + space +'lastname'是否可能比這個長? – 2014-09-05 21:58:08
似乎很多人今天有相同的功課:http://stackoverflow.com/questions/25691729/how-do-i-assign-values-from-text-file-to-a-structure-of-arrays-在-C – 2014-09-05 22:04:04