#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
static int counts = 0;
struct student {
vector <float> score;
};
class CView {
private:
vector<student> data;
public:
CView() {
load();
}
~CView() {
save();
}
student InPut() {
student st;
float sc;
for (int i = 0; i < 3; i++) {
cin >> sc;
st.score.push_back(sc);
}
return st;
}
void Insert(const student st) {
data.push_back(st);
counts++;
}
void Print() {
for (auto& x : data) {
for (int i = 0; i < 3; i++) {
cout << x.score[i] << " ";
}
cout << endl;
}
}
void load() {
ifstream ifile("student.txt");
if (!ifile)
{
cerr << "file open error " << endl;
return;
}
ifile >> counts;
student st;
float s = 0;
for (int i = 0; i < counts; ++i)
{
for (int j = 0; j < 3; ++j)
{
ifile >> s;
st.score.push_back(s);
}
data.push_back(st);
}
}
void save() {
ofstream ofile("student.txt");
if (!ofile)
{
cerr << "file open error " << endl;
return;
}
student st;
ofile << data.size() << endl;
for (auto x : data) {
for (int i = 0; i < 3; i++) {
ofile << x.score[i] << " ";
}
cout << endl;
}
}
};
int main() {
CView cont;
student stu;
int selete = 0;
do {
cout << "1.插入" << endl;
cout << "2.打印" << endl;
cout << "3.退出" << endl;
cin >> selete;
switch (selete) {
case 1:
stu = cont.InPut();
cont.Insert(stu);
break;
case 2:
cont.Print();
break;
case 3:
break;
default:
cout << "输入错误" << endl;
}
} while (selete != 0);
return 0;
}
第一次运行程序打印时是正常的
第二次载入数据之后打印就成这样了
我想到的是在读取数据时出错了,经过调式,我发现在读取时将数据读到了同一个容器中,但是在不改动结构的基础上不知道怎么改