程序终止索引外部



我必须编写一个程序,该程序接受字符串输入,并在没有特殊字符的情况下排序字符串,但是即使循环仅运行到字符串<</p>

#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异常。

最新更新