我試圖用struct/union實現將文本文件讀入一個cstring數組。首先,這是我的文本文件看起來像:將任意數字的特定單詞讀入一個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
現在,忽視了明顯的亞洲popstar引用我的講師決定,以填補這個例子 - 我希望能夠之前閱讀的第一個數字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;
}
這是處理所有的陣列信息我最後的文本文件,是什麼樣子:
任何幫助表示讚賞,感謝。
被他們強迫你使用工會的這種方式?對我來說這似乎是一個有爭議的設計 –
是的,標題幾乎是以這種方式預先格式化的。你可以使用 –
來使用STL類,比如'string'嗎?你的問題被標記爲「C++」,所以我假設答案是肯定的,但是在我想到一個你不會被允許使用的解決方案之前詢問是更好的問題 –