Click here to Skip to main content
15,906,574 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
hi !

i want to extract an integer from a string but i dont know how, for example if i have the folowing string :
i just want to get as a result : 100

thank you for your help :)

You can use this code:
std::string num ("");
std::string str ("100Mbps");

for (int i=0; i < str.length(); i++) {
    char c =;
    if (c >= '0' && c <= '9')
       num += c; // or num.push_back(c) or num.append(c);

Good luck.
Share this answer

I thought there was also a strtoi, but I can't seem to find it, maybe its not part of the standard library.
Share this answer
Ron Beyer 18-Aug-13 21:42pm    
Was atoi, but seems to be depreciated and replaced by strtol.
Sergey Alexandrovich Kryukov 18-Aug-13 21:57pm    
By the way, all those functions is total and complete lame.

Documentation says that return value is 0 in case of invalid input format, and, specifically "No-throw guarantee: this function never throws exceptions". The real translation of this politically correct specification means: "developers of this function did not have a clue what the exception is".

This way, the input "0" and "unknown trash" will give identical result.
"#include" forever! :-)

Your answer is 5ed. :-)

Ron Beyer 18-Aug-13 22:12pm    
I certainly don't agree with the "never throw guarantee" with most code, if I give it a bad value, it needs to tell me, not just return a valid value for invalid input. Thanks!
Klaus-Werner Konrad 19-Aug-13 7:29am    
"0" will give you an other value in *endptr (*endptr == (ptr+1)) than "trash" (*endptr==ptr)
Sergey Alexandrovich Kryukov 19-Aug-13 10:05am    
Good point, thank you, Claus-Werner. However, this is still lame.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900