簡體   English   中英

從文件中讀取數據並存儲到結構數組中

[英]Read data from file and store into an array of structs

因此,我需要幫助創建一個程序,該程序將打開文件並將文件中的數據讀入結構數組,然后計算各種事物,如最高,最低,平均和標准偏差。 現在,我更關心如何讀取實際文件並將其放入結構數組中。

以下是作業的說明:

- 您將從輸入文件scores.txt中讀取輸入數據(將在練習曲中發布); 數據格式為(studentID,名字,姓氏,考試1,考試2和考試3)。

- 將從文件中讀取一個學生的每個數據行,然后將其分配給結構變量。 因此,您將需要一個結構數組來存儲從輸入文件中讀取的所有數據。 這將是一維數組。

- 一旦從文件中讀取數據到陣列,就需要計算並顯示每個考試的以下統計數據。

這是數據文件:

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函數,只是在main函數中執行它,但我決定反對它使我的主要看起來有點“干凈”。 在我調用openFile函數之后,我考慮過只執行inFile >> arr[]但是它似乎不太可能工作或有意義。

我的建議:

  1. 添加運算符函數以從流中讀取一個StudentData對象。
  2. main添加while循環。 在循環的每次迭代中,讀取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

這應該將您的所有數據讀入數組,您需要一個增量器

ifstream inStream; inStream.open( “scores.txt”);

 while (!inStream.eof())
 {

       inStream >> StudentData arr[SIZE];

 };
 inStream.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM