Link to home
Start Free TrialLog in
Avatar of bail3yz
bail3yz

asked on

How can I edit this string in C++?

Hi,

I have some data in a string.. and I need to extract pieces of it.

The string has this info in it

"The cost: $150 (Total)"

I need to get 150 out of the string.. I dont need any of the other info.. how can I do this?

Also.. originally the data is in a char*, so if we can do it somehow with a char* that works too

Thanks

Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Several thoughts come to mind.  If it really is a char* type (not an ANSI string), sscanf should do nicely.

int Value;

  if (sscanf ("The cost: $150 (Total)", "[^0-9]%d", &Value) > 0)
    // Value was extracted.


Good Luck,
Kent
ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> find that start and end index of the number
Heh, I forgot to point out you then use substr and stringstream to convert the string representation to a integer one =/
http://www.cplusplus.com/reference/string/string/substr/
http://www.cplusplus.com/reference/iostream/stringstream/
Avatar of bail3yz
bail3yz

ASKER

Hi evilrix,

I actually ended up using just find (which I didnt know about until your post!) and substr.. because the # is always different but the rest of the text is always the same..

Thanks for the help!
If the rest of the string is always the same (guaranteed), you can simply do :

        const char* str = "The cost: $150 (Total)";
        int cost = atoi(str + strlen("The cost: $"));
Or if you want to avoid the strlen call :

        int cost = atoi(str + 11));