Furkan Bozkurt
Furkan Bozkurt

Reputation: 104

How do I take only numbers from a string?

I need to copy numbers from a string to another string in c++. I wrote this code but it only copies the first number in the string.

class Number{
    private:
        string value;
    public:
        void Print(){
            cout<<value;
        }
        Number(string dgr){
            int i = 0; 
            for(int j=0; j<dgr.length();j++){
                if(isdigit(dgr[j])){
                    value[i]=dgr[j];
                    i++;
                }
            }
        }
};

Upvotes: 0

Views: 220

Answers (3)

Andreea S
Andreea S

Reputation: 26

I am unable to comment but as a response to: Wow thanks but still have a problem. when I input "a6s54da65sd4a" it returns "6546541877994624". What's that "1877994624" part? When I recompile and run it the number won't change.

I can't see the value being reset or initialized anywhere. What is the size of value? I would use append instead of accessing various elements in "value". Something like value.append(1, dgr[j]);

Upvotes: 0

Serge
Serge

Reputation: 12344

operator [] in the string can be used to modify already existing characters. It does not extend the length of the string. So, if you pre-assign some value to 'value' you would see the characters modified there (up to the length of this string).

What you rally need is something like this:

value += dgr[j];

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

With the code you show, the string value is an empty string. That means all indexing into it will be out of bounds and you will have undefined behavior.

Instead append the characters to the string:

value += dgr[j];

Upvotes: 2

Related Questions