How do I extract the numbers from string in C?
There are many ways to parse a string containing numbers. If you expect the string to have a fixed format with 2 integers, the simplest solution is to use sscanf()
:
#include <stdio.h>
int parse2numbers(const char *str) {
int a, b;
// sscanf returns the number of successful conversions
int n = sscanf(str, "%d%d", &a, &b);
if (n == 2) {
printf("success: a=%d, b=%d\n", a, b);
return 1;
}
if (n == 1) {
printf("failure: only one number provided: a=%d, str=%s\n", a, str);
return 0;
}
if (n == 0) {
printf("failure: invalid format: %s\n", str);
return 1;
}
printf("failure: encoding error: n=%d, str=%s\n", n, str);
return 0;
}
If the string can contain a variable number of integers, you could use strtol()
to parse one integer at a time:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
void parse_numbers(const char *str) {
long a;
char *p;
for (;; str = p) {
errno = 0;
// strtol returns a long int
// updates `p` to point after the number in the source string
// sets errno in case of overflow and returns the closest long int
a = strtol(str, &p, 10);
if (p == str)
break;
if (errno != 0) {
printf("overflow detected: ");
}
printf("got %ld\n", a);
}
if (*str) {
printf("extra characters: |%s|\n", str);
}
}