由于每行有一条记录,所以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给你的老师和同学们凹痕。
请问您是否更具体,也可以代码形式评论您的文件请 – blazerix
不要成为“代码研讨会” - 告诉我们您到目前为止尝试过的方法 –
我建议您使用结构并搜索“stackoverflow C++读取文件结构“ –