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:
#include <iostream>
#include <string>
#include <cctype>
usingnamespace 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.
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.