Search code examples
c++stringerase

Why can't I erase string's numeric characters?


I want to erase all numbers in a string (eventually all symbols and white spaces) and keep all letter characters in the string. What I am trying to ultimately do is search for palindromes from large blocks of text.

With what I got right now it will erase the numbers; plus all other non numeric characters after the first numeric character that gets erased. I want to know why this is doing this and what I can do to make it erase only the numeric characters.

#include <iostream>
#include <string>
#include <cctype>
#include <ctype.h>
#include <iterator>
using namespace std;

int main()
{
bool con = true;
while (con == true)
{
cout << "Enter a string: ";
string input;
getline(cin, input);

/** here is where I am attempting to erase all numeric characters in input string**/    
for(int i=0; i<input.length(); i++){

    if(isdigit(input.at(i))){

        string::iterator it;
        it=input.begin()+i;
        input.erase(i);
    break;
    }
}

string go;

cout << input << endl;

    cout << "Continue? y/n " << endl;
    getline(cin, go);
    if( go != "y")
        con = false;


}
system("pause");
return 0;
}

Solution

  • for(int i=0; i<input.length(); i++){
    
        if(isdigit(input.at(i))){
    
            string::iterator it;
            it=input.begin()+i;
            input.erase(i);
        break;
        }
    }
    

    I don`t like that code snippet: decide that to use iterators or indexes, I think you shoudn`t mix them.
    There is error in you code: when you erase from a string it`s length also changes(so for loop will not work, instead use while loop)

    string::iterator it = input.begin();
    
        while (it != input.end())
        {
             while( it != input.end() && isdigit(*it))
             {
                  it = input.erase(it);
             }
             if (it != input.end())
                 ++it;
        }