获取错误"Expression: string subscript out of range"

Getting error "Expression: string subscript out of range"

本文关键字:out of subscript range 取错误 Expression 获取 string      更新时间:2023-10-16

我不明白这里的问题。我已经研究过了,它编译得很好,但是当我运行程序时,它给了我"Debug Assertion Failed!"错误和上面的解释。

#include <iostream>
#include <string>
using namespace std;

bool checkVowel(char ch)
{
 switch(ch)
 {
     case 'a':
     case 'A':
     case 'e':
     case 'E':
     case 'i':
     case 'I':
     case 'o':
     case 'O':
     case 'u':
     case 'U':
          return true;
     default:
          return false;
 }}
int main()
{
string str;
char ch;
cout<<"Please enter a string, all vowels will be removed: ";
cin >> str;
for (int i=0;i=str.length();i++)
{
 if (checkVowel(str[i]))
     {
        str=str.erase(i);
 }}
cout << str;
}

这里有一个错误:

i=str.length()
应:

i < str.length()

在初始代码中,当字符串非空时,i=str.length()将始终返回true。因此,结果是您将超出字符串。

此外,当您找到一个元音时,您不希望增加索引,否则您将跳过下一个字符:

for (int i = 0; i < str.length(); )
{
    if (checkVowel(str[i]))
    {
        str.erase(i,1);
    }else{
        i++;
    }
}

最后一件事:str=str.erase(i);是不必要的,只要str.erase(i,1);就足够了。(您需要第二个参数为注释中指出的1)

如果条件错误,则应为for (int i=0;i <= str.length();i++)

也可以使用STL remove_if

remove_if(str.begin(), str.end(), checkVowel);

完整的程序将被。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool checkVowel(char ch){
    switch(ch){
        case 'a':
        case 'A':
        case 'e':
        case 'E':
        case 'i':
        case 'I':
        case 'o':
        case 'O':
        case 'u':
        case 'U':
            return true;
        default:
            return false;
    }
}
int main(){
    string str;
    char ch;
    cout << "Please enter a string, all vowels will be removed: ";
    cin >> str;
    remove_if(str.begin(), str.end(), checkVowel);
    cout << str;
}