0
已在createStructs()中註釋掉的行向我提供了有關的錯誤。我正在嘗試掃描來自文本文件的信息列表,並在加載文件後給我一個程序崩潰。當它崩潰時,它將輸出輸出,但是以一種非常奇怪的方式。這裏是我的代碼:C編程結構運行時錯誤
#define MAX 71
#define SIZE 14
typedef struct {
char first[7];
char initial[1];
char last[9];
char street[16];
char city[11];
char state[2];
int zipcode[5];
int age;
char sex[1];
int tenure;
double salary;
} Employee;
insert main method just calling the functions
void strsub(char buf[], char sub[], int start, int end) {
int i, j = 0;
for (j = 0, i = start; i <= end; i++, j++) {
sub[j] = buf[i];
}
sub[j] = '\0';
}
void createStructs(Employee inWorkers[]) {
int i = 0;
char buf[MAX];
char temp[SIZE];
if (!(fp = fopen("payfile.txt", "r"))) {
printf("payfile.txt could not be opened for input.");
exit(1);
}
while (!(feof(fp))) {
fgets(buf, MAX, fp);
strsub(buf, inWorkers[i].first, 0, 6);
strsub(buf, inWorkers[i].initial, 8, 8);
strsub(buf, inWorkers[i].last, 10, 18);
strsub(buf, inWorkers[i].street, 20, 35);
strsub(buf, inWorkers[i].city, 37, 47);
strsub(buf, inWorkers[i].state, 49, 50);
strsub(buf, temp, 52, 56);
//inWorkers[i].zipcode = atoi(temp);
strsub(buf, temp, 58, 59);
inWorkers[i].age = atoi(temp);
strsub(buf, inWorkers[i].sex, 61, 61);
strsub(buf, temp, 63, 63);
inWorkers[i].tenure = atoi(temp);
strsub(buf, temp, 65, 70);
inWorkers[i].salary = atof(temp);
i++;
}
}
void printNames(Employee workers[]) {
for (int i = 0; i < SIZE; i++) {
printf("%s %s %s %s %s %s %d %d %s %d %.2lf", workers[i].first, workers[i].initial, workers[i].last,
workers[i].street, workers[i].city, workers[i].state, workers[i].zipcode, workers[i].age,
workers[i].sex, workers[i].tenure, workers[i].salary);
}
}
將'int zipcode [5];'更改爲'int zipcode;'(除非您確實需要每位員工5個郵編)。在嘗試'fopen'之前,你還需要聲明'FILE * fp = NULL;'。並看到[**爲什麼是「while(!feof(file))」總是錯誤的?**](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) –