我正在尝试使用 struct/union 实现将文本文件读入 cstring 数组。首先,这是我的文本文件的样子:
F South Korea
Male Psy Park Jae Sang
31 - 12 - 1977
3 CSCI114 55 CSCI103 44 GangNam 100
S Female Super Junior
5 - 8 - 1978
2 CSCI114 60 CSCI103 80
F People Republic Of China
Unknown James Bond
11 - 12 - 1976
4 CSCI114 54 CSCI124 66 CSCI007 99 CSCI123 28
现在,忽略明显的亚洲流行歌星引用,我的讲师决定用这个例子来填充 - 我希望能够阅读 CSCI 之前的第一个数字,这是数字或课程及其各自的成绩,并自动(循环)它文本文件中的所有 3 名(或更多)学生。
我还没有为我在这里试图描述的内容编写任何代码,但这是我到目前为止所拥有的。
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int MAX = 80;
struct Birthday
{
char day[MAX];
char month[MAX];
char year[MAX];
};
struct Local
{
char name[MAX];
char gender[MAX];
Birthday bd;
char subjects [MAX];
};
struct Foreigner
{
char name[MAX];
char nationality[MAX];
char gender[MAX];
Birthday bd;
char subjects [MAX];
};
union Student
{
Local localStudent;
Foreigner foreignStudent;
};
enum CountryType {S, F};
struct UowStudents
{
CountryType ct;
Student st;
};
int fileToArray (fstream& afile, char fileName [], UowStudents& x);
int main ()
{
srand(time_t(NULL));
fstream afile;
UowStudents x [MAX];
char fileName[MAX];
cout << "Enter filename: ";
cin >> fileName;
int size = fileToArray (afile, fileName, *x);
}
int fileToArray (fstream& afile, char fileName [], UowStudents& x)
{
afile.open(fileName, ios::in);
if (!afile)
{
cout << fileName << "could not be opened for read" << endl;
exit (-1);
}
//file to array.
char locale;
char dateJunk;
afile >> locale;
afile.getline(x.st.foreignStudent.nationality, MAX);
afile >> x.st.foreignStudent.gender;
afile.getline(x.st.foreignStudent.name, MAX);
afile >> x.st.foreignStudent.bd.day;
afile >> dateJunk;
afile >> x.st.foreignStudent.bd.month;
afile >> dateJunk;
afile >> x.st.foreignStudent.bd.year;
//Tests my cstring arrays to see everything is copied in correctly.
cout << locale << " " << x.st.foreignStudent.nationality;
cout << endl;
cout << x.st.foreignStudent.gender;
cout << x.st.foreignStudent.name;
cout << endl;
cout << x.st.foreignStudent.bd.day << " - ";
cout << x.st.foreignStudent.bd.month << " - ";
cout << x.st.foreignStudent.bd.year;
return 0;
}
这是我处理完所有数组信息的最终文本文件,如下所示:
任何帮助表示赞赏,谢谢。