我正在学习如何使用fstream
和dynamic array
,该程序应该打印出txt file
中的所有数据,并可以执行诸如排序,删除性别或计算平均值年级。 但事实证明,代码很混乱,数组很难访问。C++如何将文件读入动态数组并访问数组元素
代码:
struct studentData{
string branch;
string name;
char gender;
double grade;
int number;
int total;
};
int main() {
int line_count = 0;
ifstream file_in;
int couter = 0;
file_in.open("student.txt");
if(!file_in.good())
{
cout << "Eror, could not open the file." << endl;
file_in.clear();
return -1;
}
line_count = openFileTest(file_in);
file_in.clear();
file_in.seekg(ios::beg);
studentData* p_studentData = new studentData[line_count];
loadStudentData(file_in, p_studentData,couter);
displayStudentData(p_studentData, line_count,couter);
delete [] p_studentData;
file_in.close();
return 0;
}
int openFileTest(ifstream& file_in)
{
string temp;
int linecount = 0;
while(getline(file_in, temp))
{
linecount ++;
}
return linecount;
}
void loadStudentData(ifstream& file_in,studentData* p_studentData,int couter)
{
int temp ;
file_in >> p_studentData -> total ;
temp = p_studentData->total;
for(int i=0;i<temp;i++)
{
file_in >> p_studentData->branch >> p_studentData->number ;
for(int k=0;k<p_studentData[i].number;k++)
{
file_in >> p_studentData[k].name >> p_studentData[k].gender >> p_studentData[k].grade ;
}
p_studentData++;
}
return;
}
void displayStudentData(studentData* p_studentData, int count_line,int couter)
{
cout << p_studentData->total << endl;
int temp = p_studentData->total ;
for(int i=0;i<temp;i++)
{
cout << p_studentData[i].branch << " " ;
cout << p_studentData[i].number << endl;
for(int j=0;j<p_studentData[i].number;j++)
{
cout << p_studentData[j].name << " " << p_studentData[j].gender << " " << p_studentData[j].grade << endl;
}
}
return;
}
我得到的输出是:
[要将输出读取到'std :: setw'。](http://en.cppreference.com/w/cpp/io/manip/setw) – user4581301
如果您的文件格式尚未修复,我建议使用json解析器,例如https://github.com/nlohmann/json – schorsch312