一个缓冲区引发的血案
已有 433 次阅读 2009-12-18 17:35呵呵,标题党一下。
今天帮一个朋友写段代码,当时拿到题目,觉得很简单,三下五除二便写出了代码,但运行一下发现出了问题。
题目要求:输入数据到一个文件,然后读出数据并输出。
代码:(编辑器没有代码插入功能,格式乱的没法说,我的编程风格可是很好的哦)
#include <stdio.h>
#define NUM 2
struct STU
{
char name[20];
char sex;
int age;
int score;
} student[NUM];
int main()
{
int i;
FILE *fp = NULL;
for (i = 0; i < NUM; ++i)
{
printf("Input the NO.%d\'s info\n", i + 1);
printf("Name: ");
scanf("%s", student[i].name);
fflush(stdin); //清空输入缓冲区
printf("Sex(M or F): ");
scanf("%c", &student[i].sex);
printf("Age: ");
scanf("%d", &student[i].age);
printf("Score: ");
scanf("%d", &student[i].score);
}
while ((fp = fopen("date.txt", "w+")) == NULL);
for (i = 0; i < NUM; ++i)
{
fprintf(fp, "%s, %c, %d, %d\n", student[i].name, student[i].sex, student[i].age, student[i].score);
}
fclose(fp);
while ((fp = fopen("date.txt", "r")) == NULL);
for (i = 0; i < NUM; ++i)
{
fscanf(fp, "%s, %c, %d, %d\n", student[i].name, &student[i].sex, &student[i].age, &student[i].score);
}
fclose(fp);
for (i = 0; i < NUM; ++i)
{
printf("%s %c, %d, %d\n", student[i].name, student[i].sex, student[i].age, student[i].score);
}
return 0;
}
第一次运行的时候,并没有fflush(stdin);这句,导致运行结果一直不对,仔细检查后发现是输入缓冲区出了问题,加上后问题解决。
关于输入缓冲区的详细情况,请大家参考《C缺陷与陷阱》。
记录一下,告诫自己以后不要再犯这种错误。
发表评论 评论 (0 个评论)