Reputation: 391
I have a string that looks like this: {opt,2}{home,4}...
I have to scan opt and 2 into a string and integer. I am doing this:
char str[40] = "{opt,2}{home,4}";
char s[20];
int *x;
sscanf(str, "{%[^,],%[0-9]}", s,&x);
This segfaults. What is the right way?
Upvotes: 1
Views: 514
Reputation: 11237
To scan text like that, you don't need regex, you could just use simple scanf
specifiers.
char s[16]; /* The string in the pair */
int n; /* The integer in the pair */
int len; /* The length of the pair */
for (; sscanf(buf, "{%[^,],%d}%n", s, &n, &len) == 2; buf += len) {
/* use str and n */
}
The %n
specifier simply receives the number of characters read in the sscanf
call, and stores it in the matching argument (in this case, len
). We use this value so that we can increment the buf
that is being read from, so that the next string-int pair may be read.
Upvotes: 2