【发布时间】:2017-08-10 13:14:35
【问题描述】:
我编写了一个小程序,将学生姓名和最终成绩写入文件,然后读取该文件并打印出来。我还是 C 的新手,我正在玩输入验证,但是在将它与结构一起使用时遇到了问题。当我运行我的函数时,它会很好地检查案例,但它不会将正确的输入存储到 studentFinalGrades 中。所以当我去打印文件时,它从来没有存储最终成绩的输入。关于如何解决这个问题的任何想法?或者关于如何以另一种方式进行输入验证的建议? 这是我的代码:
#include <stdio.h>
#include <stdlib.h>
//struct of students
struct students
{
char name[50];
char lastName[50];
char studentFinalGrade[50];
};
//myfunctions (at bottom of main)
char check_letterGrade(void);
void clear_input_buffer(void);
int main()
{
// in check_letterGrade
char input;
if (input != '\n')
{
clear_input_buffer();
}
//dynamic array
struct students a[2],b[2];
FILE *fptr;
int i;
//opens file.txt
fptr=fopen("file.txt","wb");
//Loop to enter in all student data and grades at once (only did 5 students because it takes forever to fill it out)
for (i=0;i<2;++i)
{
fflush(stdin);
printf("Enter Student Name: ");
scanf("%s",&a[i].name);
printf("Enter Student Last Name: ");
scanf("%s",&a[i].lastName);
printf("What is students Final Grade?:");
check_letterGrade();
// scanf("%s",&a[i].studentFinalGrade);
}
//writes user input to a file and then closes file
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
//opens and reads file
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
//Printing all Studens names and grades entered into the file.
int j = 0;
for (i=0;i<2;++i)
{
j ++;
printf("\nStudent %d :\n",j);
printf("Name: %s\nLast Name: %s\nFinal Grade: %s\n\n", b[i].name,b[i].lastName,b[i].studentFinalGrade);
}
fclose(fptr);//close file when done reading.
}//end main
//function to check user validation on correct letter grades entered.
char check_letterGrade(void)
{
char input;
int ch;
//If input is not all of these things then it will tell user to please enter a correct letter grade
// it will then check for new line (which should clear from the buffer and allow new entry) hopefully
while (scanf("%s", &input) != 1 || (input != 'A' && input != 'B'&& input != 'C'&& input != 'D'&& input != 'F'))
{
if (input != '\n') // only take leftover input if there is leftover input
{
while ((ch = getchar()) != '\n') ;
}
printf("Please enter a correct letter grade: ");
}
return input;
}
//clears buffer
void clear_input_buffer(void)
{
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
}
【问题讨论】:
标签: arrays validation input file-io struct