2017-05-10 2 views
1

학생 이름 중기 및 최종 점수를 받고 txt 파일에 쓰기를 원하지만 루프를 사용할 때 결코 학생 이름을 얻지 못합니다. 그것은 항상 그것을 놓친다. 루프에서 feof를 어떻게 사용할 수 있습니까? 중간 이름과 최종 점수를 얻고 점수를 통해 평균을 계산하고 싶습니다. 사용자가 파일의 끝을 누를 때까지 항상 이름과 점수를 얻어야합니다.while 루프와 함께 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"); 
} 
+0

[관련 질문] (http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong?rq=1) – InternetAussie

답변

0

몇 가지 :

첫째, 결코 결코 결코 결코 결코하지 사용 gets - 그것은 위험하다, 그것은 코드에서 오류 및/또는 대규모 보안 구멍의 포인트를 소개합니다 2011 년 버전의 언어 표준에서 표준 라이브러리에서 제거되었습니다. 대신 fgets를 사용

fgets(nameOfStudents, sizeof nameOfStudents, stdin); 

둘째, while(!feof(fp)) 항상 잘못된 것입니다. fp에서 입력 할 때 너무 자주 한 번 반복됩니다. fp의 출력에서는 의미가 없습니다.

당신은 당신의 루프를 제어 할 수 fgets의 결과를 사용할 수 있습니다 : 당신이 터미널에서 데이터를 입력이 완료되면

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

가 어느 Ctrl 키Z 또는 Ctrl 키를 사용하여 EOF 신호 D (플랫폼에 따라 다름).

세 번째로 mainvoid이 아니라 int을 반환합니다.

int main(void) 

대신 사용하십시오.

마지막으로, 파일에 학생의 이름을 작성하는

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

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

로 변경합니다.

다른 문제가 있지만 변경을하고 도움이되지 않는지 확인하십시오.

관련 문제