【问题标题】:How can I use feof with while loop?如何将 feof 与 while 循环一起使用?
【发布时间】:2017-10-09 01:35:35
【问题描述】:

我想获取学生姓名中期和期末分数并将它们写入 txt 文件,但是当我使用循环时,它永远不会获取学生姓名。它总是给它一个错过。如何在循环中使用 feof?我想得到学生的名字中期和期末分数,并从得到的分数中计算平均值,它必须始终得到名字和分数,直到用户按下文件结尾。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<conio.h>

void main()
{
FILE *Points;

char namesOfStudents[10];
int pointsOfStudents[1][2];
double AverageOfStudents[1];
int i=0,j=1;
int numberOfStudents;

Points = fopen("C:\\Users\\Toshiba\\Desktop\\PointsOfStudent.txt", "a+");
fprintf(Points, "Name\t\t 1.Grade\t2.Grade\t\tAverage\n");
/*  printf("How many students will you enter: ");
scanf("%d",&numberOfStudents);*/

//while (!feof(Points))

printf("Please enter new students name: ");
gets(namesOfStudents);
printf("\nPlease enter new students first point: ");
scanf("%d",&pointsOfStudents[0][0]);
printf("\nPlease enter new students second point: ");
scanf("%d",&pointsOfStudents[0][1]);


        for (; i < strlen(namesOfStudents); i++)
            {
                fprintf(Points, "%c", namesOfStudents[i]); //To write 
     student name to file

            }
        fprintf(Points,"\t\t   ");

        fprintf(Points,"%d\t\t",pointsOfStudents[0][0]);  //to write 
student's first point
        fprintf(Points,"%d\t\t",pointsOfStudents[0][1]);  //to write 
student's second point  

        fprintf(Points,"%d\n",(pointsOfStudents[0][0]+pointsOfStudents[0]
[1])/2);    //to calculate and write average 
        system("cls");

        fclose(Points);

system("Pause");
}

【问题讨论】:

标签: c file loops for-loop while-loop


【解决方案1】:

几件事:

首先,NEVER NEVER NEVER NEVER 使用 gets - 这是危险的,它引入故障点和/或您的代码中存在巨大的安全漏洞,并且从 2011 版语言标准开始,它已从标准库中删除。请改用fgets

fgets( nameOfStudents, sizeof nameOfStudents, stdin );

其次,while( !feof( fp ) ) 总是错误的。从fp 输入时,它会经常循环一次。输出到fp,没有意义。

您可以使用fgets 的结果来控制您的循环:

while ( fgets( nameOfStudents, sizeof nameOfStudents, stdin ) )
{
  ...
}

当您从终端输入完数据后,使用 CtrlZCtrlD 发出 EOF kbd>(取决于您的平台)。

第三,main 返回int,而不是void;使用

int main( void )

改为。

最后,改变

for (; i < strlen(namesOfStudents); i++)
{
  fprintf(Points, "%c", namesOfStudents[i]); //To write student name to file
}

fprintf( Points, "%s", nameOfStudents );

将学生姓名写入文件。

还有其他问题,但进行这些更改,看看是否没有帮助。

【讨论】:

    猜你喜欢
    • 2013-07-06
    • 2020-08-25
    • 1970-01-01
    • 2014-04-11
    • 2014-01-09
    • 1970-01-01
    • 2011-08-06
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多