【问题标题】:program terminates on Index out-of-range程序在索引超出范围时终止
【发布时间】:2018-04-27 09:22:27
【问题描述】:

我必须编写一个程序,它接受字符串输入并输出没有特殊字符的排序字符串,但即使循环只运行到字符串末尾,它也会抛出索引越界异常

#include <iostream>
#include <string.h>
using namespace std;
int main(){
    string mes="";
    string tem;
    cin>>tem;
    for (int i=0;i<tem.length();i++){
        char ch=tem.at(i);
        if((ch<=65&&ch<=90)||(ch>=97&&ch<=122))
            mes+=ch;
        else
            continue;
    }
    cout<<mes;
    for(int i=0;i<tem.length();i++){
        int small=(int)mes.at(i);
        int spos=i;
        for(int j=i;j<tem.length();j++){
            int a=(int)mes.at(j);
            if(a<small){
                small=a;
                spos=j;
            }
        }
        char temp=' ';
        temp=mes.at(i);
        mes.at(i)=mes.at(spos);
        mes.at(spos)=temp;
    }
    cout<<mes;
}

这是错误信息:

terminate 'std::out_of_range' what(): basic_string::at: __n(即 3)>= this->size()(即 3)

【问题讨论】:

  • 你应该在从mes读取的循环中使用mes.length()

标签: c++ string


【解决方案1】:
for(int i=0;i<tem.length();i++){
    int small=(int)mes.at(i);

您遍历tem 的索引,但读取大小不同的mes

【讨论】:

  • 注意:你的程序可以在很多层次上改进:编写小函数,使用std::(尤其是&lt;algorithm&gt;)的工具,避免多余的代码(生活@ 987654326@), ...
【解决方案2】:

您可能需要先更正

if((ch<=65&&ch<=90)||(ch>=97&&ch<=122))

to

if(( ch >= 65 && ch <= 90) || ( ch >= 97 && ch <= 122))

第二: 第二个字符串 (mes) 的大小将始终小于第一个字符串 (tem) 的大小。但在第二个循环中,您使用 i 导航第二个字符串 (mes),这会导致 out of range 异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2022-01-10
    • 2016-03-31
    相关资源
    最近更新 更多