【发布时间】:2015-06-22 05:14:08
【问题描述】:
在使用 cin 输入某些值后,我正在尝试覆盖文件中的数据。我面临的问题是,应该修改文件的函数实际上并没有正确执行。
这是场景,我使用注册函数添加这些数据
代码:
// register a student to the system
void Student::registerStudent(string name, int studentNo, char gender) {
outStream.open("StudentRecord.txt", ios_base::app);
outStream << left << setw(15) << studentNo << setw(15) << gender << right << name << endl;
outStream.close();
}
我添加了 3 次数据,我得到了
Batman 11 M
BatGirl 22 F
Joker 33 M
现在问题来了,我尝试通过添加额外的主题分数来修改 蝙蝠侠 行
我想要的结果:
Batman 11 M 100 22 55 22 33
BatGirl 22 F
Joker 33 M
名字后面的数字是科目分数。
但是,当我运行程序来修改特定行时,我得到了这个
BatGirl 22 F -858993460 -858993460 -858993460 -858993460 -858993460
Batman 11 M 12 86 44 24 55
Joker 33 M -858993460 -858993460 -858993460 -858993460 -858993460
这里是具体行修改的代码
// Function to modify a student's exam scores.
void Student::modifyScore(string newName, 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 >> name >> studentNo>> gender>> indian >> english >> math >> history >> moral;
data[name] = make_tuple(studentNo, gender,indian, english, math, history, moral);
}
studentRec.close();
// Modify data
auto it = data.find(newName) ; // gets current student record from the map
if (it == data.end()) // student not in map, that's an error
return ;
// now it->second holds your student data
// an auto here could be better, but we want to be sure of type
auto studentNo = get<0>(it->second) ;
auto gender = get<1>(it->second) ;
data[newName] = make_tuple(studentNo, gender, 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(studentNo, gender, newIndian,newEnglish, newMath, newHistory, newMoral) = entry->second;
//int average = averageScore(newIndian,newEnglish, newMath, newHistory, newMoral);
ofs << left << setw(15) << entry->first << setw(15) << studentNo << setw(15) << gender << setw(15) << newIndian << setw(15) << newEnglish << setw(15) << right << newMath << setw(15) << newHistory << setw(15) << newMoral << endl;
}
ofs.close();
}
为了清楚起见,modifyScore 的参数是
newName --> is to find the name in the file
newIndian --> Subject scores
newEnglish --> Subject scores
newMath --> Subject scores
newHistory --> Subject scores
newMoral --> Subject scores
请指出我犯错的地方。谢谢!
【问题讨论】:
-
如果您要求流提取数字但它不能,因为流中的该位置没有数字,它会失败并且您希望将数字提取到的变量不变。在您的情况下,这些变量也未初始化,因此它们可以包含任何内容。在不知道数字不存在的情况下,如果不知道您的期望是什么,就很难给出建议。
标签: c++