我想從冒號分隔文件中提取信息到類對象中。文件的每一行都以相同的格式設置。下面是該文件的前幾行:從冒號分隔文件提取信息 - C++
s:Charles:Babbage:80:530213286:1133764834:mechanical engineering:3.8
e:Marissa:Meyer:37:549114177:53321:ceo:4456000
s:Alonzo:Church:92:586312110:1100539644:mathematics:4.0
e:Dana:Ulery:74:573811211:23451:engineer:124569
這是一個學校項目,目的是教給我們的類繼承。我們有一個基類Person和兩個子類Student和Employee。我們應該將學生的信息導入並存儲到Employee對象和Student對象中。我有一個每個類的對象數組;我將學生排序爲Student對象數組,同樣適用於員工,並將所有人添加到People對象數組中。
我不知道該怎麼做才能用分隔符來獲取每條信息。現在我正在嘗試使用.getline,但它似乎沒有工作。如何使用此函數(或其他函數)將分隔符之間的信息提取到char數組中?這裏是我到目前爲止的數據是針對僱員的情況:
ifstream fin;
char* tempImport;
tempImport = new char[50];
int* tempIntArray;
tempIntArray = new int[10];
double tempDouble;
int tempInt;
// get the specifier of student or employee
fin.getline(tempImport, ':');
if(tempImport[0]=='e'){
// get first name
fin.getline(tempImport, ':');
employees[employeeIndex].setFirstName(tempImport);
allPeople[personIndex].setFirstName(tempImport);
// get last name
fin.getline(tempImport, ':');
employees[employeeIndex].setFirstName(tempImport);
allPeople[personIndex].setFirstName(tempImport);
// get age
fin.getline(tempImport, ':');
employees[employeeIndex].setAge(tempImport[0] - 0);
allPeople[personIndex].setAge(tempImport[0] - 0);
// get SSN
fin.getline(tempImport, ':');
for(int i=0;i<9;i++){
tempIntArray[i] = tempImport[i] - 0;
}
employees[employeeIndex].setSsn(tempIntArray);
allPeople[personIndex].setSsn(tempIntArray);
// get Employee ID
fin.getline(tempImport, ':');
for(int i=0;i<5;i++){
tempIntArray[i] = tempImport[i] - 0;
}
employees[employeeIndex].setEmpID(tempIntArray);
// get title
fin.getline(tempImport, ':');
employees[employeeIndex].setTitle(tempImport);
// get salary
fin >> tempDouble;
employees[employeeIndex].setSalary(tempInt);
employeeIndex++;
personIndex++;
}
當您使用調試程序逐步完成程序時發生了什麼? –
請使用''0''而不是48。許多人沒有意識到48是字符零的ASCII代碼的十進制值。 –
爲什麼使用'new'運算符和動態內存?這是C++,而不是Java。絕對必要時只使用動態內存。研究「內存泄漏C++」以獲得關於雙面效應的更多信息。 –