Erasing characters from a string

I am currently trying to remove anything that is not a digit or the letter X. However, for some reason it's not working when I try to use the erase() command
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 <stdio.h>
using namespace std;
bool checkDigits(string input)
{
        for(int i=0; i<input.length(); i++)
    {
        if(!isdigit(input[i]) && toupper(input[i]) != 'X')
        {
            input.erase(i,1);
        }
    }
}
int main()
{
    char c;
    string input;
    while((c = cin.get()) != EOF)
    {
            input += c;
    }
    checkDigits(input);
    cout << input;
}
You're passing the string by value to the checkDigits function by value. Any operations in the function won't impact the string declared in main.

You could actually use a predicate and the remove_if function to achieve this without loops as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <algorithm>

bool predicate( char c )
{
    return ( !isdigit( c ) && c != 'X' );
}

int main( int argc, char* argv[] )
{
    std::string my_str = "ABCX1X2DEF";
    
    my_str.erase( std::remove_if( my_str.begin(), my_str.end(), predicate ), my_str.end() );
    std::cout << "My string is " << my_str << std::endl;

    return 0;
}
Last edited on
Topic archived. No new replies allowed.