How to extract all integers (numbers) from a string (null terminated character sequences) in C++

1 Answer

0 votes
#include <iostream>

using namespace std;

void extract_numbers(char s[]) { 
    int num = 0;
       
    char *p = s;
    while (*p) {
        if (isdigit(*p)) {
            num = num * 10 + strtol(p, &p, 10);
        } 
        else {
            p++;
            if (num != 0) cout << num << endl;
            num = 0;
        }
    }
} 
     
int main() 
{ 
    char s[] = "1c++32 ja60val"; 
 
    extract_numbers(s); 
     
    return 0; 
} 
 
 
/*
run:
 
1
32
60
 
*/

 



answered May 27, 2019 by avibootz
...