2017-07-29 116 views
1

如果已經得到回答,我表示歉意,我試着搜索並找不到爲什麼這不起作用。從文件中讀取行時出錯

我正在編寫一個程序來讀取文件,該文件包含一個名稱後跟5個整數的行。我試圖將名稱讀入一個字符串數組,然後將5個整數讀入另一個數組中。當我運行我的代碼時,第一個名字和前5個整數按預期讀取,但是當循環繼續時,沒有其他任何內容被讀入數組中。

#include <iostream> 
#include <iomanip> 
#include <fstream> 
#include <string> 

using namespace std; 

int main() 
{ 
    int row, col, average, students = 0; 
    string storage; 

    string names[15]; 
    double test[15][5]; 
    double grade[15]; 

    ifstream inFile; 
    ofstream outFile; 

    inFile.open("testScores.txt"); 
    outFile.open("averages.out"); 

    for (students; !inFile.eof(); students++) 
    { 
     //getline(inFile, storage, '\n'); 
     inFile >> names[students]; 
     for (col = 0; col <= 5; col++) 
     { 
      inFile >> test[students][col]; 
     } 
     inFile.ignore('\n'); 

    } 

我知道使用命名空間std是皺眉,但這是我的老師希望我們完成代碼的方式。我嘗試添加一個忽略來跳到輸入中的下一行,但這似乎沒有奏效。我也嘗試使用getline使用臨時存儲字符串,但不確定這是最好的方式去做。任何幫助將不勝感激。謝謝

輸入文件 -

Johnson 85 83 77 91 76 
    Aniston 80 90 95 93 48 
    Cooper 78 81 11 90 73 
    Gupta 92 83 30 69 87 
    Blair 23 45 96 38 59 
    Clark 60 85 45 39 67 
    Kennedy 77 31 52 74 83 
    Bronson 93 94 89 77 97 
    Sunny 79 85 28 93 82 
    Smith 85 72 49 75 63 
+0

閱讀本https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong然後告訴我們您的輸入文件是什麼樣子。這和其他許多重複的內容也可能相同。 https://stackoverflow.com/questions/1744665/need-help-with-getline –

+1

它是col <= 5'還是col <5'? – iBug

+0

@iBug我猜這也是問題,但沒有輸入文件,這只是一個猜測。但是,是的,試圖將一個字母讀入一個數字會導致錯誤,並且由於沒有錯誤檢查,所以不會被注意到,而其他所有讀取都會失敗。 –

回答

0

我用getline函數和字符串流

它更容易與函數getline處理,因爲你可以在一個字符串 編寫和修改或分析此字符串

和stringstream是一種很酷的方式來從字符串中提取數據

下面是我要如何去做

you have to include sstream 

string line{""}; 

if (inFile.is_open()) { 
    while (getline(inFile,line)){ 
    names[students] = line.substr(0, line.find(" ")); 
    stringstream ss; 
    ss << line.substr(line.find(" ")); 

    for(size_t i{0}; i < 5; ++i){ 
     ss >> dec >> test[students][i]; 
    } 
    ++students; 
    } 

    inFile.close(); 
} else { 
     cout << "could not read file"; 
}