따라서 파일을 열고 파일의 데이터를 구조체 배열로 읽어 들인 다음 최고, 최저, 평균 및 표준 편차와 같은 다양한 것을 계산하는 프로그램을 만드는 데 도움이 필요합니다. 지금은 실제 파일을 읽고 구조체 배열에 배치하는 방법에 대해 더 걱정하고 있습니다.
할당에 대한 지침은 다음과 같습니다.
-입력 파일 scores.txt에서 입력 데이터를 읽습니다 (Etudes에 게시 됨). 데이터는 형식 (studentID, 이름, 성, exam1, exam2 및 exam3)입니다.
-한 학생에 대한 각 데이터 줄은 파일에서 읽은 다음 구조체 변수에 할당됩니다. 결과적으로 입력 파일에서 읽은 모든 데이터를 저장하려면 구조체 배열이 필요합니다. 이것은 1 차원 배열이됩니다.
-파일에서 어레이로 데이터를 읽은 후에는 각 시험에 대해 다음 통계를 계산하고 표시해야합니다.
다음은 데이터 파일입니다.
1234 David Dalton 82 86 80
9138 Shirley Gross 90 98 94
3124 Cynthia Morley 87 84 82
4532 Albert Roberts 56 89 78
5678 Amelia Pauls 90 87 65
6134 Samson Smith 29 65 33
7874 Michael Garett 91 92 92
8026 Melissa Downey 74 75 89
9893 Gabe Yu 69 66 68
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
struct StudentData
{
int studentID;
string first_name;
string last_name;
int exam1;
int exam2;
int exam3;
};
const int SIZE = 20;
// Function prototypes
void openInputFile(ifstream &, string);
int main()
{
// Variables
//int lowest, highest;
//double average, standardDeviation;
StudentData arr[SIZE];
ifstream inFile;
string inFileName = "scores.txt";
// Call function to read data in file
openInputFile(inFile, inFileName);
//Close input file
inFile.close();
system("PAUSE");
return 0;
}
/**
* Pre-condition:
* Post-condition:
*/
void openInputFile(ifstream &inFile, string inFileName)
{
//Open the file
inFile.open(inFileName);
//Input validation
if (!inFile)
{
cout << "Error to open file." << endl;
cout << endl;
return;
}
}
지금은 주석에 넣은 변수를 무시하고 있습니다. 나는 openFile 함수를 포기하고 단지 주 함수에서 수행하는 것에 대해 생각하고 있었지만 내 주된 모습을 조금 "더 깨끗하게"만들기로 결정했습니다. 나는 inFile >> arr[]
openFile 함수를 호출 한 후에 그냥하려고 생각 했지만 작동하거나 말이되지 않을 것 같았다.
나의 제안:
StudentData
스트림에서 하나의 객체 를 읽는 연산자 함수를 추가 합니다.while
루프를 추가합니다 main
. 루프의 각 반복에서StudentData
std::istream& operator>>(std::istream& in, StudentData& st)
{
return (in >> st.studentID
>> st.first_name
>> st.last_name
>> st.exam1
>> st.exam2
>> st.exam3);
}
그리고 main
:
openInputFile(inFile, inFileName);
size_t numItems = 0;
while ( inFile >> arr[numItems] )
++numItems;
마지막에 numItems
항목을 arr
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다