【发布时间】:2018-02-18 21:54:52
【问题描述】:
我正在尝试使用 C 中的结构存储课程名称和我上该课程的日期的信息。存储名称不是问题。当我尝试将多天(工作日作为整数,即星期一 = 1)存储在数组中时,就会出现问题。
这就是我所拥有的:
#include<stdio.h>
#include<string.h>
struct lessons{
char name[20];
int day[3];
};
changelessons(){
int i, k;
struct lessons give[1], receive[1];
FILE *fptr;
fptr = fopen("lessons","wb");
fflush(stdin);
printf("\n\t ~ Change lessons ~");
printf("\n\nWhat's the lesson called?: ");
gets(give[0].name);
printf("\nHow many days do you have it?\n");
scanf("%d", &k);
for(i = 0; i < k; i++); { // Asks the weekday number for each day you have the lesson
printf("What day is lesson %d?: ", i);
scanf("%d", &give[0].day[i]);
}
fwrite(give, sizeof(give), 1, fptr);
fclose(fptr);
fptr = fopen("lessons", "rb");
fread(receive, sizeof(receive), 1, fptr);
printf("\n\t ~ Updated information: ~\n\nLesson name: %s\nDay: %d", receive[0].name, receive[0].day[1]);
for(i = 1; i < k; i++); { // Prints the extra weekdays if there are any
printf(", day: %d", receive[0].day[i]);
}
printf("\n\n");
fclose(fptr);
}
showlessons(){
struct lessons give[1], receive[1];
FILE *fptr;
fptr = fopen("lessons", "rb");
fread(receive, sizeof(receive), 1, fptr);
printf("\t ~ Current information: ~ \n\nLesson name: %s\nDay: %d\n\n", receive[0].name, receive[0].day[0]);
}
int main(){
showlessons();
changelessons();
return 0;
}
此外,在第一个 for 循环中,无论 k 等于多少,它只会循环一次。
提前感谢您的帮助!
【问题讨论】:
-
for(i = 0; i < k; i++); {在这里,您为 for 的主体使用了单语句。所以下面的{}body 会被执行一次。