Reputation: 61
I was wondering how to extract various numbers from a string. I understand that strtol works, however it appears to only work for the first digit.
Here is my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(){
long v1, v2, v3;
char str[20] = "16,23";
char *d;
v1 = strtol(str, &d, 10);
v2 = strtol(str, &d, 10);
printf("string is %s\nv1 is:%i\nv2 is:%d\n",str , v1,v2);
return 0;
}
In this example I would like to output v1 = 16 and v2 = 23.
Another example, if the str was "12,23,34", I would like v3= 34
Thanks in advance :)
Upvotes: 1
Views: 1505
Reputation: 153457
Use long strtol(const char * nptr, char ** endptr, int base)
. The endptr
allows for easy subsequent parsing as that is where parsing stopped.
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
int string_to_longs(const char *s) {
#define N 3
long v[N];
int i;
for (i=0; i<N; i++) {
errno = 0;
char *end;
v[i] = strtol(s, &end, 10);
if (errno) return -1; // overflow
if (s == end) return -1; // no conversion
printf("v[%d] = %ld\n", i, v[i]);
if (*end == 0) break; // we are done
if (*end != ',') return -1; // missing comma
s = (const char *) (end + 1);
}
return i;
}
int main(void) {
string_to_longs("16,23");
string_to_longs("12,23,34");
return 0;
}
Upvotes: 2
Reputation: 352
strtol
just converts a character array to a long int. It stops when it finds the first character that wouldn't make sense into interpreting an integer from.
There is a function in string.h named strtok which helps you tokenize a string.
Beware that strtok
mutates the original character array contents.
Upvotes: 1
Reputation: 134326
You can have many approaches. One of them is to make use of the endptr
, populated by the previous strtol()
call as the source of the next strtol()
.
Otherwise, for a better and flexible approach, you also have an option of using strtok()
with a predefined delimiter (the ,
here) to get the tokens one by one and convert them to int
or long
(as you wish) until strtok()
returns NULL.
Upvotes: 2