CDT CDT - 3 years ago 110
C Question

How to extract numbers from string in c?

Say I have a string like

and I want to extract all the numbers
234, 349, 20
, what should I do ?

Answer Source

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if (isdigit(*p)) { // Upon finding a digit, ...
        long val = strtol(p, &p, 10); // Read a number, ...
        printf("%ld\n", val); // and print it.
    } else { // Otherwise, move on to the next character.

Link to ideone.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download