C++运行抛出std::out_of_range异常 字符串存数字逐位对比报错求助
问题原因分析
- 首先
std::out_of_range报错的直接原因是字符串下标越界访问:你用at()方法访问字符串下标时,传入了超出合法范围的索引。
你代码里的两个循环都是for (int j=0; j<length; j++),循环体内访问numeriai.at(j+1),当j等于length-1时,j+1就等于length,而string的合法下标范围是0 ~ length-1,就会触发越界异常。 - 第二个常见错误:
if (nice = true)是赋值操作,不是相等判断,会永远为真,逻辑完全不符合预期,应该改成if (nice == true)或者直接if (nice)。 - 额外逻辑问题:第一个循环的逻辑是判断字符串所有相邻位是否严格递减,但是你初始化
nice为false,如果字符串长度是1的话循环不会执行,nice还是false,不会输出;第二个循环是判断所有相邻位是否完全相等,同样存在长度为1的越界和逻辑问题。
修复后的参考代码
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { int n; fstream f("telef.txt"); f >> n; string numeriai; for (int i=0; i<n; i++) { f >> numeriai; bool nice = false; int length = numeriai.length(); // 长度小于2的字符串不需要对比相邻位,可根据需求调整这里的逻辑 if (length >= 2) { // 判断是否严格递减 nice = true; for (int j=0; j < length - 1; j++) { char ch = numeriai.at(j); char chh = numeriai.at(j+1); if (ch <= chh) { nice = false; break; } } if (nice) { cout << numeriai << endl; } // 判断是否所有位相等 nice = true; for (int k=0; k < length - 1; k++) { char ch = numeriai.at(k); char chh = numeriai.at(k+1); if (ch != chh) { nice = false; break; } } if (nice) { cout << numeriai << endl; } } } return 0; }
修改点说明
- 循环条件修改为
j < length -1,保证j+1最大为length-1,不会越界 - 将if判断中的
=改为逻辑判断,修正了永远为真的问题 - 先初始化
nice为true,再循环判断不满足的情况就设为false跳出,符合正常的判断逻辑 - 增加了长度判断,长度小于2的字符串不会进入对比逻辑,避免不必要的错误
内容的提问来源于stack exchange,提问作者Sade
相关产品推荐
相关产品推荐

