C++程序中cin读取nosearch时异常退出,ignore/clear无效求助
问题根源与解决方案
核心错误
你的代码中动态数组的分配方式完全错误:
int *arr = new int(tenn*10); // 错误:仅分配1个int,初始值为tenn*10
正确的数组分配应该使用方括号,用于指定数组元素数量:
int *arr = new int[tenn*10]; // 正确:分配tenn*10个int元素的数组
为什么会导致输入崩溃
这种错误会引发内存越界访问的未定义行为:后续的数组填充、排序、输出循环都在读写超出单个int的内存区域,这会破坏程序的栈结构或标准输入流的内部状态,最终导致cin >> nosearch执行时程序直接终止。
额外建议
使用动态数组后记得在程序结束前释放内存,避免内存泄漏:
delete[] arr; // 放在main函数末尾
原代码(错误片段标记)
#include <iostream> #include <stdlib.h> #include <ctime> #include "search.hpp" //a function called sarch is here, program quits before sarch is called. using namespace std; int main () { srand(time(0)); int tenn; int minrange; int maxrange; cout << "Enter the number of integers: "; cin >> tenn; cout << endl << "Enter the lower limit: "; cin >> minrange; cout << endl << "Enter the upper limit: "; cin >> maxrange; // 此处为错误的数组分配 int *arr = new int(tenn*10); for (int i = 0; i < tenn*10; i++){ *(arr+i) = (rand() % maxrange) + minrange; } cout << "list, unsorted: " << endl; for (int i = 0; i < tenn*10; i++){ cout << *(arr+i) << " "; } cout << endl; for (int i = 0; i < tenn*10; i++){ int low = i; for (int j = i; j < tenn*10; j++){ if (*(arr+j) < *(arr+low)){ low = j; } } int temp = *(arr+i); *(arr+i) = *(arr+low); *(arr+low) = temp; } cout << "sorted list: " << endl; for (int i = 0; i < tenn*10; i++){ cout << *(arr+i) << " "; } cout << endl; int nosearch; cout << "Enter the number of values you wish to search for: " << endl; //The next cin will fail cin >> nosearch; cout << "v"; //more code here... }
终端运行原程序情况
>./Needle.exe Enter the number of integers: 2 Enter the lower limit: 0 Enter the upper limit: 10 list, unsorted: 9 4 6 2 4 5 2 9 1 4 7 8 3 4 9 4 6 7 9 9 sorted list: 1 2 2 3 4 4 4 4 4 5 6 6 7 7 8 9 9 9 9 9 Enter the number of values you wish to search for: 3 >
内容的提问来源于stack exchange,提问作者Chickendragon
相关产品推荐
相关产品推荐

