2016-09-23 85 views
-8

我有一个看起来像这样的文件:计算文本文件的数字数据

89369865 19 20 17 14 10 5 16 20 20 12 7 49 82 7 
55959810 36 18 18 19 20 17 20 17 7 15 9 75 81 10 
56569325 20 7 14 12 20 18 18 9 17 12 5 61 98 9 
92457613 35 6 15 19 20 20 13 18 17 8 11 40 57 10 
81596872 25 20 11 14 18 19 16 12 13 10 12 68 86 9 
79916777 39 20 20 8 18 19 11 14 13 18 17 61 97 7 

81383418 38 10 12 18 17 17 16 16 19 19 4 72 92 3 

只是50个学生总。

我已经通过代码打开文件
1.我该如何计算每一行的分隔?
2.我该如何创建一个循环来分别计算每一行并给出每行的总数?

谢谢!

+0

请问您是否更具体,也可以代码形式评论您的文件请 – blazerix

+2

不要成为“代码研讨会” - 告诉我们您到目前为止尝试过的方法 –

+0

我建议您使用结构并搜索“stackoverflow C++读取文件结构“ –

回答

1

由于每行有一条记录,所以std::getline将成为您的朋友,std::string也将成为您的朋友。

让我们试一下:

std::string record_text; 
std::getline(my_data_file, record_text); 

我们可以用std::istringstream帮助转换文本记录到的数字:

std::istringstream record_stream(record_text); 
std::vector<int> student_values; 
int student_id; 
record_stream >> student_id; 
int value; 
while (record_stream >> value) 
{ 
    student_values.push_back(value); 
} 

我使用std::vector包含学生价值观;您可能需要使用其他容器。

编辑1:重载提取运算符
如果你想打动你的老师和同学,你应该记录与struct模型和输入超载运营商:

struct Student_Record 
{ 
    int id; 
    std::vector<int> values; 
    friend std::istream& operator>>(istream& input, Student_Record& sr); 
}; 
std::istream& operator>>(istream& input, Student_Record& sr) 
{ 
    // See above on how to read a line of data. 
    // Be sure to use "sr." when accessing the structure variables, 
    // such as sr.id 
    return input; 
} 

重载运算符允许你有更简单的输入:

std::vector<Student_Record> database; 
Student_Record sr; 
while (my_data_file >> sr) 
{ 
    database.push_back(sr); 
} 

一定要推荐StackOverflow给你的老师和同学们凹痕。

+0

@TheOneandOnlyChemistryBlob:因为今天是太平洋海岸的星期五,我认为我会很好,并且提供一个基础。有时候,微调可以提供帮助。我没有提供整个程序。只有一些先进的技术。 –

+0

@ThomasMatthews很好地完成了先生+1 – blazerix

+1

或者我应该更诚实一些,并且说我为信誉点回答了它。 :-) –