2017-09-06 34 views
0

這是一種被稱爲grades.txt文本文件:如何從文本文件讀取不同類型的數據到多個數組? C++

John Sebastian 90 80 85 90  75 70 89 80 90  86 88 89 99 100 

Brown Ford   40 60 80 85  60 90 100 80 90  83 81 89 97 90 

我需要閱讀所有的數據,並把它們放在不同的陣列。前四個級別是考試,其次是測驗,第三個是家庭作業。

#include <iostream> 
#include <fstream> 

using namespace std; 

void letter_grade(string names[][2], int exams[][4], int quiz[][5], int homeworks[][5], float grades[2][2]); 

int main() { 

ifstream Openfile("grades.txt"); 


string names[2][2]; 
int exams[4][4]; 
int quiz[5][5]; 
int homeworks[5][5]; 

if(Openfile.is_open()){ 
for(int i = 0 ; i<2 ; i++){ 
    Openfile >> names[i][0]; 
} 
    for(int j = 0 ; j<2; j++){ 
     Openfile >> names[j][1]; 
    } 
} 
    else{ 
    cout << "File is not open." << endl; 
} 
if(Openfile.is_open()){ 
    for(int x = 0 ; x<4 ; x++){ 
     for(int y = 0; y<4 ; y++){ 
      Openfile >> exams[x][y]; 
     } 
    } 
} 


    return 0; 
} 

所以陣列,我計劃將是這樣的:

names[0][0] = John 
names[1][0] = Sebastian 
names[0][1] = Brown 
names[1][1] = Ford   

等。但我無法做到這一點,代碼不斷閱讀考試結果並將其寫入名稱數組中。

然後,我將從數組中計算這些學生的成績,並將結果保存在不同的文件中,如果我可以從文本文件中讀取數據,我會這樣做。

+1

讀取文件中(和寫入到陣列)明智行明智,不是列。 –

+0

[Here](https://stackoverflow.com/questions/23047052/why-does-reading-a-record-struct-fields-from-stdistream-fail-and-how-can-i-fi)'sa number的建議如何處理。首先爲每條記錄提供一個數據結構。 – user0042

回答

0

多維數組不包含單個組件或成員值的語義信息。你必須在數據的含義和頭部陣列中的位置之間進行翻譯。而是使用適當的數據結構來使你的代碼有意義。

您的具體的例子可以這樣寫:

// the record data 
struct StudentScore { 
    std::string firstname, lastname; 
    int exams[4]; 
    int quizzes[5]; 
    int homeworks[5]; 
}; 
// parse the text, assuming data is well formatted 
StudentScore parse_one_record (std::istream &is) { 
    StudentScore score{}; 
    is >> score.firstname >> score.lastname; 
    for (auto &exam: score.exams) is >> exam; 
    for (auto &quiz: score.quizzes) is >> quiz; 
    for (auto &homework: score.homeworks) is >> homework; 
    // consume any trailing whitespaces including LF 
    is >> std::ws; 
    return score; 
} 

int main (int, char *[]) { 
    auto file = std::ifstream("grades.txt"); 
    file >> std::ws; 
    auto records = std::vector<StudentScore>{}; 
    // assume the file is well formatted. 
    while (!file.eof()) { 
     records.push_back(parse_one_record(file)); 
    } 
    // now you can begin processing your data 
} 
+0

請看看這個:https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong –

+0

這是正確的,我的代碼不正確處理例外情況,但它旨在演示除了如何編寫工業強度C++代碼之外的基本概念。正如我在代碼的評論中已經指出的那樣,這個代碼只處理格式良好的數據。當然在生產代碼中,當談到解析或處理不可信數據源的任何任務時,它永遠不會太防守。 –

相關問題