C++程序重启后记录序号重置,如何读取历史计数值实现连续自增?
解决记录序号连续自增的问题
原程序的问题在于每次启动都硬将序号变量i初始化为1,完全忽略文件中已有的历史记录,导致新增记录序号无法延续。要解决这个问题,只需要在程序启动时先读取文件,找出历史最大序号,再以此为基础设置新记录的起始序号。
修改步骤
- 新增
getMaxId()函数,负责读取文件并返回历史最大序号; - 将原代码中
int i = 1;替换为int i = getMaxId() + 1;,让新记录从正确的序号开始; - 处理文件不存在的边界情况(此时最大序号为0,新记录仍从1开始)。
修改后的完整代码
#include <iostream> #include <fstream> #include <algorithm> using namespace std; // 获取文件中记录的最大序号 int getMaxId() { ifstream inFile("tableData.txt"); if (!inFile.is_open()) { return 0; // 文件不存在或无法打开,返回0,新记录从1开始 } int maxId = 0; int id; string firstName, userName, password; // 遍历所有记录,找出最大序号 while (inFile >> id >> firstName >> userName >> password) { if (id > maxId) { maxId = id; } } inFile.close(); return maxId; } int main(){ cout << "\n"; // 初始化序号为历史最大序号+1 int i = getMaxId() + 1; while(i > 0){ cout << "Input Data" << endl; string firstName, userName, password; char character; ofstream userWriteFile("tableData.txt" , ios::app); cout << "Name: "; cin >> firstName; cout << "User-Name: "; cin >> userName; cout << "Password: "; cin >> password; userWriteFile << "\n"; int n = i; userWriteFile << n << " " ; userWriteFile << firstName << "\t\t"; userWriteFile << userName << "\t\t"; userWriteFile << password << "\t\t"; userWriteFile.close(); cout << "Do You Want more Entries or Not (Press the Key Y(Yes) / N(No)): "; cin >> character; if(character == 'y' || character == 'Y'){ i++; } else if(character == 'n' || character == 'N'){ // 打印所有记录 ifstream userReadFile("tableData.txt"); if (!userReadFile.is_open()) { cout << "No records found.\n"; break; } while (userReadFile >> n >> firstName >> userName >> password) { cout << "\n"; cout << n << "." << " " << firstName << " " << userName << " " << password << " " << "\n"; } userReadFile.close(); break; } else{ cout << "invalid Character"; break; } } return 0; }
额外优化点
- 简化了原代码中
n = i + 0的冗余写法,直接用n = i; - 优化了读取记录的循环逻辑,避免原代码中
while(1)加eof判断的潜在问题; - 添加了读取文件失败时的提示信息。
内容的提问来源于stack exchange,提问作者sarim nadeem
相关产品推荐
相关产品推荐

