C_C++

(C언어) 구조체를 이용한 성적처리: 파일에서 데이터 읽기

고니자니 2022. 10. 27. 21:38
반응형

#구조체 #성적처리 #데이터 #파일 #읽기 #fopen

 

데이터 파일로 부터 데이터를 읽어서 구조체 배열에 기억시킨 후, 이를 이용해서 성적처리를 하는 예제입니다.

 

데이터 파일을 다음과 같습니다.

1 정경환 99 97 95
2 이순신 77 88 100
3 홍길동 88 87 89
4 이런 91 92 93
5 이나라가 94 78 96
6 왜이래 100 100 100

 

구조체와 파일에서 데이터를 읽는 C언어 코드입니다.

- 가능하면 전역변수를 사용하지 않도록 작성했습니다.

- 데이터를 읽는 함수와 출력하는 함수를 만들어서 처리하도록 했습니다.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#define N	100

struct SUNGJUK
{
	int bunho;
	char name[10];
	int kor;
	int eng;
	int mat;
};

void read_data(struct SUNGJUK list[], int *cnt)
{
	// 데이터 파일로 부터 데이터를 읽음

	FILE* fp;
	int i = 0;

	fp = fopen("data.txt", "r");
	if (fp == NULL)
	{
		printf("data.txt 파일을 읽을 수 없습니다.\n");
		exit(1);
	}

	while(fscanf(fp, "%d", &list[i].bunho) != EOF)
	{
		fscanf(fp, "%s %d %d %d",
			list[i].name, &list[i].kor, &list[i].eng, &list[i].mat);
		i++;
	}
	*cnt = i;    // 인원수를 포인터를 이용해서 호출한 곳으로 반환합니다.
    
    fclose(fp);
}

void print(struct SUNGJUK list[], int cnt)
{
	// 출력
	int i, tot;

	printf("번호 이름     국어 영어 수학 총점    평균\n");
	printf("-----------------------------------------\n");
	for (i = 0; i < cnt; i++)
	{
		tot = list[i].kor + list[i].eng + list[i].mat;

		printf(" %d   %-8s  %3d  %3d  %3d  %3d  %6.2f\n",
			list[i].bunho, list[i].name, list[i].kor, list[i].eng, list[i].mat,
			tot, (float)tot / 3);
	}
}

int main()
{
	struct SUNGJUK list[N];
	int cnt = 0;

	read_data(list, &cnt);   // cnt: 읽은 데이터 파일 개수(인원수)을 돌려 받음
	print(list, cnt);

	return 0;
}

(Output)

\

(복사 가능한 텍스트↓↓↓)

번호 이름     국어 영어 수학 총점    평균
-----------------------------------------
 1   정경환     99   97   95  291   97.00
 2   이순신     77   88  100  265   88.33
 3   홍길동     88   87   89  264   88.00
 4   이런       91   92   93  276   92.00
 5   이나라가   94   78   96  268   89.33
 6   왜이래    100  100  100  300  100.00

 

 


더 단순한(간단한) 성적처리를 원한다면 ... ↙↙↙

https://gonyzany.tistory.com/89

 

(C언어) 구조체를 이용한 성적처리

#구조체 #struct #성적처리 #총점 #평균 구조체를 이용해서 성적처리를 하는 간단한 예제입니다. #include struct SUNGJUK { int bunho; char name[10]; int kor; int eng; int mat; }; int main() { struct SUNGJ..

gonyzany.tistory.com

 

728x90
반응형