c ++表达式:字符串下标超出范围错误

时间:2015-07-03 01:10:49

标签: c++

你好,我是编程的新手但每次运行这段代码我都会收到错误“c ++ Expression:string subscript out of range”我很确定错误是在第二个for循环中

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

int main()
{
string x;
string n;
cin >> x;


for (int i = 0; i <= x.length(); i++){
    if (x[i] == 'a' || x[i] == 'e' || x[i] == 'i' || x[i] == 'o' || x[i] == 'u' || x[i] == 'y')
    {
        x[i] = ' ';

    }


}
x.erase(remove_if(x.begin(), x.end(), isspace), x.end());
int f = x.length() * 2;
for (int i = 0; i <f-1; i+=2){

    n[i] = '.';

}
cout << n << endl;

}

4 个答案:

答案 0 :(得分:3)

for (int i = 0; i <= x.length(); i++)

应该是:

for (int i = 0; i < x.length(); i++)

因为索引从0

开始

答案 1 :(得分:2)

  1. x[x.length()]超出范围
  2. 当n的大小为0时,
  3. 无法使用n[index],请使用n.push_back()

     for (int i = 0; i < x.length(); i++){  //error
            if (x[i] == 'a' || x[i] == 'e' || x[i] == 'i' || x[i] == 'o' || x[i] == 'u' || x[i] == 'y')
            {
                x[i] = ' ';
    
        }
    
    
        }
        x.erase(remove_if(x.begin(), x.end(), isspace), x.end());
        int f = x.length() * 2;
        for (int i = 0; i <f-1; i+=2){
    
            n[i] = '.';  // n.push_back('.');
    
        }
        cout << n <
    

    &LT; ENDL;

答案 2 :(得分:0)

如果您尝试从输入字符串中删除所有元音,则无需运行两个单独的循环。您已经在使用std :: remove_if,只需添加以下代码中显示的lambda即可获得所需的输出。

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

int main() {
    std::string str = "This is test of vowels aeiou to be removed. Also the upper case AEIOU.";

    std::cout << "Original String: " << str << std::endl;

    str.erase(std::remove_if(str.begin(), str.end(), [](char x) {
        return (x == 'a'|| x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'y'
                || x == 'A'|| x == 'E' || x == 'I' || x == 'O' || x == 'U' || x == 'Y')

    }), str.end());
    std::cout << "String with vowels removed: " << str << std::endl;

    // Not sure what you are trying to achieve with this code.
    int f = x.length() * 2;
    for (int i = 0; i <f-1; i+=2)
    {
        n[i] = '.';
    }
    return 0;
}

以下是LiveDemo

答案 3 :(得分:0)

您有3位代码导致错误:

1)发生第一个错误是因为您应该在第一个循环条件中检查i < x.length(),而不是i <= x.length()。更好的是,计算一次长度,然后在循环条件中使用该值,以避免重复调用x.length()。你的第一个循环应该是这样的:

int length = x.length();
for (int i = 0; i < x.length(); ++i)

注意:++我比i ++更快,在这种情况下使用++我不会对逻辑产生影响。

2)您的第二个错误是由于行int f = x.length() * 2引起的,因为您将数组的长度加倍,然后使用该数字迭代数组。例如,如果你的数组的长度()为5,那么int f = x.length() * 2意味着f = 10但是如果数组的长度是5而不是访问任何数字大于4的数组(数组索引开始)在零)将产生错误。在你的第二个循环条件中你这样做

for (int i = 0; i < f-1; i+=2 ) {

    n[i] = '.' // i could easily be more than 4 at this point

}

要解决第二个问题,请从* 2

中取出int f = x.length() * 2

3)你的第三个是因为你没有给n字符串对象一个值但是你正在使用数组索引来访问它[]