2017-07-29 118 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"; 
}