本科生导师制问题之文件存取累加

发布时间 2023-06-25 16:05:53作者: Arkiya

在小学期的过程中,我选择了一个本科生导师制的问题,主要数据结构是广义表,在编写功能的时候有一个统计某导师所有的学生数量,其中包括研究生、本科生两种,为此我编写了一个函数,具体如下


void updateFile(const string& filename, const string& tutorName, int updatedNumber1, int updatedNumber2) {
ifstream inputFile(filename);
vector lines;
string line;


// 读取文件内容
while (getline(inputFile, line)) {
	lines.push_back(line);
}

inputFile.close();

// 在文件中查找对应导师的行
for (int i = 0; i < lines.size(); i++) {
	if (lines[i].find(tutorName) != string::npos) {
		// 更新对应导师的行
		int pos = lines[i].find("研究生、本科生的人数分别为:");
		string prefix = lines[i].substr(0, pos);
		string suffix = lines[i].substr(pos + strlen("研究生、本科生的人数分别为:"));

		// 解析当前的研究生和本科生人数
		int currentNumber1 = 0;
		int currentNumber2 = 0;
		sscanf_s(suffix.c_str(), "%d %d", &currentNumber1, &currentNumber2);

		// 累加更新后的数字
		int updatedNumber1Total = currentNumber1 + updatedNumber1;
		int updatedNumber2Total = currentNumber2 + updatedNumber2;

		// 构造更新后的行
		string newLine = prefix + "研究生、本科生的人数分别为:" + to_string(updatedNumber1Total) + " " + to_string(updatedNumber2Total);
		lines[i] = newLine;

		// 写回文件
		ofstream outputFile(filename);
		for (const string& updatedLine : lines) {
			outputFile << updatedLine << endl;
		}
		outputFile.close();

		cout << "成功累加更新导师 " << tutorName << " 的研究生、本科生人数。" << endl;

		return;
	}
}

cout << "未找到导师 " << tutorName << " 的信息。" << endl;
}

这个函数实现的是提取文件中的行,对其进行分割,然后提取出其中的数字,对数字和传入的参数进行求和,再构造一个新的行,再存储回去,说实话,写这个函数的时候真切的让我感受到了为什么大家说计算机是一个傻瓜的天才,每一个步骤都需要详细的写明,其中使用了一些以前基本没有接触过的函数,包括cstr/sscanf_s等。