我有一个程序可以从文本文件中读取数据并将数据放入一个结构中以构成一个“人”。除了读取的整数之外,所有作品都不是正确的值。他们出来的数字非常大。 感谢您的帮助。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "structs.h"
int main(void)
{
FILE *fp = NULL;
char userInput = ' ';
struct strPerson people[1];
int i;
int aPeople = 2;
int menuSelect;
while (fp == NULL)
{
fp = fopen("test", "r"); // Open File To Read
if (fp == NULL)
{
perror("Error While Loading File\n");
}
else
{
for(i = 0; i < aPeople; i++)
{
fscanf(fp, "%s%s%s%s%s%s%s%s%s%s%s%s%s%d%d%d%d%d%d%d%d%d%d",
people[i].perSurname,
people[i].perForname1,
people[i].perForname2,
people[i].perGender,
people[i].perUni.perAwardTitle,
people[i].perHomeAddress.perHAddress1,
people[i].perHomeAddress.perHAddress2,
people[i].perHomeAddress.perHAddress3,
people[i].perHomeAddress.perHAddress4,
people[i].perLocalAddress.perHAddress1,
people[i].perLocalAddress.perHAddress2,
people[i].perLocalAddress.perHAddress3,
people[i].perLocalAddress.perHAddress4,
people[i].perUni.perDOE.nDay,
people[i].perUni.perDOE.nMonth,
people[i].perUni.perDOE.nYear,
people[i].perUni.perDOG.nDay,
people[i].perUni.perDOG.nMonth,
people[i].perUni.perDOG.nYear,
people[i].perUni.perRegNumber,
people[i].strDOB.nDay,
people[i].strDOB.nMonth,
people[i].strDOB.nYear);
}
system("clear");
}
}
while (userInput != 'g')
{
system("clear");
printf(" |User System|\n"
"|------------------------------|\n"
"|------------------------------|\n"
"|A) Save Current Data To A File|\n"
"|B) Enter Details |\n"
"|C) View Details |\n"
"|D) Amend Details |\n"
"|E) Search by Award Title |\n"
"|F) Search by Surname |\n"
"|G) Shut Down |\n"
"|------------------------------|\n");
printf("Enter Function: ");
userInput = getchar();
getchar();
if (userInput == 'c')
{
for(i = 0; i < aPeople; i++)
{
printf("%d) %s %s\n", i + 1, people[i].perForname1, people[i].perSurname);
}
printf("Select Person To View Details: ");
scanf("%d", &menuSelect);
getchar();
printf("Name: %s %s %s\n",people[menuSelect-1].perForname1,
people[menuSelect-1].perForname2,
people[menuSelect-1].perSurname);
printf("DOB: %d %d %d\n", people[menuSelect-1].strDOB.nDay,
people[menuSelect-1].strDOB.nMonth,
people[menuSelect-1].strDOB.nYear);
getchar();
}
}
}
最佳答案
您没有提供 struct strPerson
的定义。
但很明显,您没有传递您尝试使用 fscanf
解析的整数的地址。这会调用未定义的行为,令人惊讶的是您的程序实际上完全可以运行。
您应该在启用警告的情况下进行编译以检测此类常见错误:gcc -Wall -W -Werror
是您的 friend 。
此外,您应该测试fscanf
的返回值以验证已解析了多少字段。任何未解析的字段都具有不确定的值。
您还试图解析 2 个结构,但结构数组只有 1 个条目。
关于C 整数正在变成大数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33059860/