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
閱讀本https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong然後告訴我們您的輸入文件是什麼樣子。這和其他許多重複的內容也可能相同。 https://stackoverflow.com/questions/1744665/need-help-with-getline –
它是col <= 5'還是col <5'? – iBug
@iBug我猜這也是問題,但沒有輸入文件,這只是一個猜測。但是,是的,試圖將一個字母讀入一個數字會導致錯誤,並且由於沒有錯誤檢查,所以不會被注意到,而其他所有讀取都會失敗。 –