目前我正面臨一個大問題,我需要將數據填充到MAP並將其寫入文件。如何不覆蓋MAP C++中的現有數據?
該文件將是這個樣子:
Name StudentNo Gender Indian English Math History Moral Average
Dragon 33899 M 100 100 100 100 100 100
下面的代碼
// Function to modify a student's exam scores.
void Student::modifyScore(string newName, int newStudentNo, char newGender, int newIndian, int newEnglish, int newMath, int newHistory, int newMoral) {
map<string, tuple<int, char,int, int, int, int, int> > data;
// Read file and fill data map
ifstream studentRec("StudentRecord.txt");
string line;
while (getline(studentRec, line))
{
string name;
int studentNo;
char gender;
int indian, english, math, history, moral;
stringstream ss(line);
ss >> studentNo>>gender>>name >> indian >> english >> math >> history >> moral;
data[name] = make_tuple(studentNo, gender,indian, english, math, history, moral);
}
studentRec.close();
auto it = data.find(newName) ;
if (it == data.end()) // student not in map, that's an error
return ;
// now it->second holds your student data,
int studentNo = get<0>(data-second) ;
char gender = get<1>(data->second) ;
// Modify data
data[newName] = make_tuple(newStudentNo, newGender ,newIndian,newEnglish, newMath, newHistory, newMoral);
// Open same file for output, overwrite existing data
ofstream ofs("StudentRecord.txt");
for (auto entry = data.begin(); entry != data.end(); ++entry)
{
tie(newStudentNo, newGender,newIndian,newEnglish, newMath, newHistory, newMoral) = entry->second;
int average = averageScore(newIndian,newEnglish, newMath, newHistory, newMoral);
ofs << left << setw(15) << entry->first << setw(15) <<newGender<<newName<< newIndian << setprecision(2) << newEnglish << setw(15) << right << newMath << setw(15) << newHistory << setw(15) << newMoral << average << endl;
}
ofs.close();
}
這段代碼的問題是,我要補充studentNo和性別作爲參數的功能,那麼只有它會覆蓋文件,但我真正想要的只是輸入一個名稱,然後修改每個主題的分數。
示例我真正想要的。
任何修改之前
Name StudentNo Gender Indian English Math History Moral Average
Dragon 33899 M 100 100 100 100 100 100
提詞
Enter the name of the student: // It will find the map that has name Dragon
--> Dragon
Enter the new score for indian subject
--> 77
Enter the new score for English subject
--> 55
Enter the new score for Math subject
--> 100
Enter the new score for History subject
--> 89
Enter the new score for Moral subject
--> 62
修改後
Name StudentNo Gender Indian English Math History Moral Average
Dragon 33899 M 77 55 100 89 62 76.6
正如你所看到的學生沒有和性別仍然存在,沒有我需要輸入的值。唯一改變的是主題分數。我將如何完成這個輸出?目前我的代碼將始終需要我輸入studentNo和性別以及輸入。
'data [newName]'覆蓋循環的每次迭代中相同的鍵,因爲您永遠不會更改它。 –
但是,我如何堅持studentNo和性別值爲一個指定的學生密鑰? – airsoftFreak