2015-04-23 175 views
1

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

下面是分配的說明:

- 您從輸入文件scores.txt讀出的輸入數據(將被張貼在 練習曲);數據格式爲(studentID,名字,姓氏,考試1, exam2和exam3)。

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

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

下面是數據文件:

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函數,只是在主函數中做,但我決定不這樣做,使我的主要看起來有點「更清潔」。在我調用openFile函數後,我認爲只是在執行inFile >> arr[],但似乎不太可能工作或有意義。

+0

爲此,您可以簡單地在循環中使用正常輸入運算符'>>'。你可能想了解'operator >>'重載。另請閱讀[爲什麼iostream :: eof內循環條件被認爲是錯誤的?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)。 –

+0

FWIW,我回答了一個類似的問題 - 顯示如何編寫自定義的'運算符>>' - [這裏](http://stackoverflow.com/questions/20623506/storing-text-file-into-a-class/20623934 ?S = 5 | 0.2236#20623934)。 –

回答

3

我的建議:

  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

0

這應該閱讀所有的數據到數組,你會希望有一個遞增器來

ifstream的inStream中; inStream.open(「scores.txt」);

while (!inStream.eof()) 
{ 

     inStream >> StudentData arr[SIZE]; 

}; 
inStream.close(); 
+3

我重申我的評論的一部分原來的問題:請閱讀[爲什麼iostream :: eof內循環條件被認爲是錯誤的?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-一個循環條件考慮的,是錯誤的)。此外,你寫的甚至不會編譯。 –

相關問題