[英]Debug Assertion Failure : expression : string subcript out of range
我正在使用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;
}
我认为这将使您的代码更具可读性。 而且它将帮助您正确调试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.