C_C++

(C++) 구조체를 이용해서 데이터 파일 읽기: fstream

고니자니 2024. 6. 10. 11:37
반응형

C++ 언어에서 구조체를 이용해서 데이터 파일을 읽어오는 예제입니다.

 

데이터 파일은 아래와 같은 형식으로 입력되어 있습니다.

데이터 파일

데이터 파일 다운로드

score_data.txt
0.00MB

#include <iostream>
#include <fstream>
using namespace std;

struct Student {
    string name;
    int kor;
    int eng;
    int mat;
};

int main() {
    Student data[100];
    string filename = "score_data.txt";
    ifstream file(filename);
    if (!file) {		//if (!file.is_open()) {
        cout << "Failed to open file: " << filename << endl;
        return false;
    }

    int n=0;
    while (file >> data[n].name >> data[n].kor >> data[n].eng >> data[n].mat) {
        n++;
    }

    file.close();

	for(int i=0; i<n; i++) {
		cout << data[i].name << "\t";
		cout << data[i].kor << "\t";
		cout << data[i].eng << "\t";
		cout << data[i].mat << endl;
	}
	
    return 0;
}

 

결과

(C++) 구조체를 이용해서 데이터 파일 읽기: fstream

728x90
반응형