Exited with return code issue

I'm very new to coding and am trying to do this assignment where all the non alpha characters must be removed from the input string. So if the input is:

-Hello, 1 world$!

The output would be:

Helloworld

I have the following written:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
   
   string str;
   int strSize;
   bool a;
   
   getline(cin,str);
   string finalStr = str;
   strSize = str.size();
   
   for (int i = 0; i < strSize; i++) {
      a = isalpha(str.at(i));
      if (a == false) {
         finalStr.erase(i,1);
      }
   }
   cout << finalStr;

   return 0;
} 


But an error occurs and I am not sure what is causing the error nor how to fix it. This is the error message:

1
2
3
Exited with return code -6 (SIGABRT).
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::erase: __pos (which is 15) > this->size() (which is 12)


Again I'm very new to this so I really haven't an idea of where to even start other than assuming its an overflow issue. Also I got no idea how the formatting on the code works sorry.
Last edited on
You will receive faster, better help if you format your source code to make it easier to read.
How to use code tags: http://www.cplusplus.com/articles/jEywvCM9/

There are other tags available.
How to use tags: http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post and add code tags.
finalStr.erase(i,1); reduces the size of the string.
Therefore, you're going to index out of bounds because you don't adjust the upper limit of your loop.
Making the new string can be done using one std::algorithm function.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
#include <iterator>

int main() {
    std::string str, finalStr;

    std::getline(std::cin, str);
    std::remove_copy_if(str.begin(), str.end(), std::back_inserter(finalStr), [](unsigned ch) {return !std::isalpha(ch); });
    std::cout << finalStr << '\n';
}



-Hello, 1 world$!

Helloworld

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;

string filter( string s, bool banned( char c ) )
{
   s.erase( remove_if( s.begin(), s.end(), banned ), s.end() );
   return s;
}


int main()
{
   string s = "-Hello, 1 world$!";
   auto filterFunction = []( char c ){ return !isalpha( c ); };
   cout << filter( s, filterFunction ) << '\n';
}
Alternatively, you can build a second string and have it replace the original string. This avoids any index invalidation.

1
2
3
4
5
6
7
8
9
10
11
12
string filter(const string& str)
{
    string out;
    for (char ch : str)
    {
        if (/* keep ch */)
        {
            out += ch;
        }
    }
    return out;
}
Last edited on
Topic archived. No new replies allowed.