Reputation: 2093
I have a version number returned as a string which looks something like "6.4.12.9", four numbers, each separated by a "."
What I would like to do is to parse the string into 4 distinct integers. Giving me
int1 = 6
int2 = 4
int3 = 12
int4 = 9
I'd normally use a regex for this but that option isn't available to me using C.
Upvotes: 1
Views: 1935
Reputation: 399881
If you're on a POSIX system, and limiting yourself to POSIX is okay, you can use the POSIX standard regular expression library by doing:
#include <regex.h>
then read the relevant manual page for the API. I would not recommend a regexp-solution for this problem to begin with, but I wanted to point out for clarity that regular expressions are often available in C. Do note that this is not "standard C", so you can't use it everywhere, only on POSIX (i.e. "Unix-like") systems.
Upvotes: 1
Reputation: 215287
If none of them will exceed 255, inet_pton
will parse it nicely for you. :-)
Upvotes: 0
Reputation: 10405
One solution using strtoul
.
int main (int argc, char const* argv[])
{
char ver[] = "6.4.12.9";
char *next = ver;
int v[4], i;
for(i = 0; i < 4; i++, next++)
v[i] = strtoul(next, &next, 10);
return 0;
}
Upvotes: 1
Reputation: 229138
You can use sscanf
int a,b,c,d;
const char *version = "1.6.3.1";
if(sscanf(version,"%d.%d.%d.%d",&a,&b,&c,&d) != 4) {
//error parsing
} else {
//ok, use the integers a,b,c,d
}
Upvotes: 8
Reputation: 55291
You could used strtok()
for this (followed by strtol()
), just make sure you're aware of the semantics of strtok()
, they're slightly unusual.
You could also use sscanf()
.
Upvotes: 0
Reputation: 318518
You can use strtoul()
to parse the string and get a pointer to the first non-numeric character. Another solution would be tokenizing the string using strtok()
and then using strtoul()
or atoi()
to get an integer.
Upvotes: 0