调试断言失败:表达式:字符串下标超出范围

Debug Assertion Failure : expression : string subcript out of range

本文关键字:范围 下标 表达式 断言 失败 调试 字符串      更新时间:2023-10-16

我使用的是VS 2013 Ultimate这里我的代码程序声明它有问题

string word_filter(string word){
    for (int i = 0; i < word.length(); i++)
        cout << word[i] << " ";
    string result;
    char tmp;
    char ch1 = word[0], ch2 = word[1], ch3 = word[3];
    if (alphabetic_order(ch1) == 37 && alphabetic_order(ch2) == 37)
        return " ";
    int i = 0;
    while (i < word.length()){
        if (alphabetic_order(word[i]) != 37) {
            tmp = word[i];
            result += tmp;
        }
        ++i;
    }
    return result;
}

请帮帮我!

看起来您正在传递一个少于四个字符的word,并且没有检查最小长度:

char ch1 = word[0], ch2 = word[1], ch3 = word[3];

上面的代码要求至少四个字符的单词,但是在代码中没有任何地方检查word.length() > 3

对不起,这可能是问题所在

ch1[0] =词,ch2 = [1], ch3 =词[3];

检查长度或在Word中输入至少4个字符的数组,否则这行代码将失败

最好按照以下方式重写代码-

string word_filter(string word){
    for (int i = 0; i < word.length(); i++)
        cout << word[i] << " ";
    string result;
    char tmp;
    char* ch = new char[word.length()];
    for(int i=0;i<word.size();i++)
    {
        ch[i] = word[i];
    }
    if (word.size()=>2)
    {
       if (alphabetic_order(ch[0]) == 37 && alphabetic_order(ch[1]) == 37)
          return " ";
    }
    int i = 0;
    while (i < word.length()){
        if (alphabetic_order(word[i]) != 37) {
            tmp = word[i];
            result += tmp;
        }
        ++i;
    }
    return result;
}

我认为这将使你的代码更易读。