Debug Assertion Failure:expression:字符串下标超出范围

时间:2014-07-21 10:27:22

标签: c++ string

我正在使用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;
}

请帮助我!

3 个答案:

答案 0 :(得分:3)

您传递的word似乎少于四个字符,并且不检查最小长度:

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

上面的代码需要至少包含四个字符的单词,但代码中的任何位置都无法检查word.length() > 3

答案 1 :(得分:2)

很抱歉,这可能是问题

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

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

答案 2 :(得分:-1)

最好以下列方式重写代码 -

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

我认为这会使您的代码更具可读性。它将帮助您正确调试。