如何用C++标准方法检测连续两次回车退出数组填充循环
问题与解决方案
需求说明
实现程序功能:
- 允许用户输入整数填充最多500个元素的数组
- 用户可通过连续两次输入空值(连续按两次回车)随时退出输入流程
- 退出后先显示原数组,排序后再次显示数组
当前问题:使用了非标准的_getche()函数读取输入,不符合C++标准要求;尝试cin.peek()和cin.get()时,输入流为空会一直等待回车,无法实现连续两次空行退出的逻辑。
标准C++实现方案
核心思路:使用std::getline()读取每一行输入,维护连续空行的计数器。读取到非空行时,将其转换为整数存入数组并重置计数器;读取到空行时递增计数器,当计数器达到2时退出输入循环。同时处理输入非整数的异常情况,避免程序崩溃。
修改后的完整代码
#include <iostream> #include <string> #include <sstream> #include <algorithm> using std::cin; using std::cout; using std::endl; using std::string; using std::getline; using std::istringstream; const int MAX_ARRAY_SIZE = 500; int GetUserArray(int arr[MAX_ARRAY_SIZE]); void DisplayVals(const int arr[MAX_ARRAY_SIZE], int count); void SortArray(int arr[MAX_ARRAY_SIZE], int count); int main() { int userArray[MAX_ARRAY_SIZE] = {0}; int valueCount = 0; valueCount = GetUserArray(userArray); cout << "\n原数组内容:" << endl; DisplayVals(userArray, valueCount); SortArray(userArray, valueCount); cout << "\n排序后数组内容:" << endl; DisplayVals(userArray, valueCount); return 0; } int GetUserArray(int arr[MAX_ARRAY_SIZE]) { int count = 0; int consecutiveEmptyLines = 0; string inputLine; cout << "请输入整数(连续按两次回车退出):" << endl; while (count < MAX_ARRAY_SIZE && consecutiveEmptyLines < 2) { cout << "输入第" << count + 1 << "个值:"; getline(cin, inputLine); if (inputLine.empty()) { consecutiveEmptyLines++; if (consecutiveEmptyLines == 2) { cout << "\n退出输入..." << endl; break; } cout << "已输入一次空行,再按一次回车退出" << endl; } else { consecutiveEmptyLines = 0; istringstream iss(inputLine); int num; if (iss >> num) { arr[count++] = num; } else { cout << "输入无效,请输入整数" << endl; } } } return count; } void DisplayVals(const int arr[MAX_ARRAY_SIZE], int count) { for (int i = 0; i < count; i++) { cout << arr[i] << " "; } cout << endl; } void SortArray(int arr[MAX_ARRAY_SIZE], int count) { // 使用标准库sort实现升序排序,若需降序可添加greater<int>() std::sort(arr, arr + count); }
关键修改说明
输入处理逻辑:
- 用
getline()读取整行输入,直接判断是否为空行,无需等待额外输入 - 用
consecutiveEmptyLines变量记录连续空行次数,达到2时退出循环 - 非空行通过
istringstream转换为整数,处理无效输入(非整数)的情况
- 用
修正原代码错误:
- 原代码将输入字符的ASCII值存入数组,现在改为实际输入的整数值
- 原
DisplayVals函数错误地将整数转为字符输出,现在直接输出整数 - 替换原手动实现的排序逻辑为标准库
std::sort(),更高效且符合规范
用户体验优化:
- 提示当前输入的是第几个值
- 第一次输入空行时给出提示,避免用户误操作退出
- 明确区分原数组和排序后数组的显示标题
内容的提问来源于stack exchange,提问作者RadLarry12
相关产品推荐
相关产品推荐

