簡體   English   中英

程序終止於索引超出范圍

[英]program terminates on Index out-of-range

我必須編寫一個程序,該程序接受字符串輸入並輸出不帶特殊字符的已排序字符串,但是即使循環僅運行到字符串末尾,它也會將索引超出范圍拋出異常

#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;
}

這是錯誤消息:

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

for(int i=0;i<tem.length();i++){
    int small=(int)mes.at(i);

您遍歷tem索引,但讀取大小不同的mes

您可能需要先更正

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異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM