C++通讯录添加联系人时行号重复且数值异常问题求助
问题分析与修复方案
问题原因
- 未初始化变量导致垃圾值:
number是局部int变量,声明时没赋值,默认是栈内存里的随机垃圾值。当number.txt为空或者读取失败时,while循环根本不会执行,number保持垃圾值,加1后写入文件,就出现了那个超大的奇怪数字。 - 字段读取逻辑缺陷:用
>>读取Address时,遇到空格就会停止读取,比如地址是"123 Main St",只会读入"123",剩下的"Main"会被当成下一个字段(Contact2),导致后续读取混乱,也可能让counter无法正确更新。
修复后的代码
#include <iostream> #include <fstream> #include <string> #include <limits> #include <sstream> using namespace std; void addContact() { string Fname, Lname, Address, Contact; // 初始化number为0,彻底避免垃圾值问题 int number = 0; int counter; string Fname2, Lname2, Address2, Contact2; cout << "Enter First Name: "; getline(cin, Fname); cout << "Enter Last Name: "; getline(cin, Lname); cout << "Enter Address: "; getline(cin, Address); cout << "Enter Contact Number: "; getline(cin, Contact); ifstream asd("number.txt"); string line; // 按行读取,避免字段含空格导致的读取错误 while (getline(asd, line)) { stringstream ss(line); // 读取每行第一个数字作为序号 ss >> counter; number = counter; } ofstream adb("number.txt", ios::app); number = number + 1; // 用分隔符|区分字段,方便后续正确读取含空格的内容 adb << number << " | " << Fname << " | " << Lname << " | " << Address << " | " << Contact << endl; }
额外优化说明
如果需要正确读取包含空格的字段,比如带空格的地址,读取时可以按行拆分:
// 读取联系人详情的示例逻辑 while (getline(asd, line)) { stringstream ss(line); string token; // 读取序号 getline(ss, token, '|'); counter = stoi(token); // 读取名字 getline(ss, Fname2, '|'); // 去除字段前后空格 Fname2.erase(0, Fname2.find_first_not_of(" ")); Fname2.erase(Fname2.find_last_not_of(" ") + 1); // 依次读取姓氏、地址、联系方式,逻辑同上 }
内容的提问来源于stack exchange,提问作者Jackie
相关产品推荐
相关产品推荐

