C++电话簿程序多次新增联系人后仅显示最新条目问题求解
问题根因
- 你声明了全局变量
i作为存储联系人的数组下标,但从未对它做初始化和自增操作:全局int类型变量默认初始值为0,所以每次调用addContact函数时,新的联系人信息都会覆盖数组索引为0的位置,连续添加多次后只有最后一次添加的内容会保留。 - 你在
viewAll函数中对整个长度为10的数组做排序和打印,包含未填充内容的空字符串:空字符串在排序时优先级高于正常的非空姓名字符串,会导致仅有的有效联系人被排到列表末尾,其余打印结果都是空行。
修复方案
1. 调整全局变量定义
删掉没用的全局循环变量i、index,新增记录当前联系人总数的变量,避免全局变量滥用:
#include <iostream> #include <cstdlib> #include <iomanip> #include <string> using namespace std; string nameArray[10]; string numberArray[10]; const int arraySize = 10; // 数组最大容量设为const更安全 int contactCount = 0; // 记录当前已添加的联系人数量
2. 重写addContact函数
新增容量判断,添加成功后自动更新联系人总数:
void addContact() { // 先判断是否存满 if (contactCount >= arraySize) { cout << "\n\t联系人数量已达上限(最多10条)" << endl; return; } // 获取用户输入 cout << "\n\tEnter contact information" << endl; cout << "\t==========================" << endl; cout << "\tEnter name: "; getline(cin, nameArray[contactCount]); cout << "\tEnter phone number: "; cin >> numberArray[contactCount]; cin.ignore(); // 添加成功,总数+1 contactCount++; }
3. 重写viewAll函数
将排序、打印范围限制在已添加的联系人范围内,循环变量改为局部变量避免全局污染:
void viewAll() { if (contactCount == 0) { cout << "\n\t当前没有联系人记录" << endl; return; } int pass = -1; string tempNumber = ""; string tempName = ""; // 仅对已添加的contactCount条记录排序 for(pass=0; pass < contactCount -1; pass++) { for(int index = 0; index < (contactCount - 1 - pass); index++) { if(nameArray[index] > nameArray[index + 1]) { tempName = nameArray[index]; nameArray[index] = nameArray[index + 1]; nameArray[index + 1] = tempName; tempNumber = numberArray[index]; numberArray[index] = numberArray[index + 1]; numberArray[index + 1] = tempNumber; } } } // 仅打印已添加的contactCount条记录 cout << endl; cout << "\t姓名\t\t手机号" << endl; cout << "\t-------------------------" << endl; for(int j=0; j < contactCount; j++) { cout << '\t' << nameArray[j] << "\t\t" << numberArray[j] << endl; } }
需求适配说明
上述修改已经满足你不需要强制一次性输入10条的要求:用户每次选择菜单1才添加1条联系人,完全由用户决定添加的时机和数量,最多支持10条,存满会自动提示。如果后续需要取消10条的上限,可以把固定数组替换为std::vector动态容器实现无限存储。
内容的提问来源于stack exchange,提问作者user15900677
相关产品推荐
相关产品推荐

