Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping square bracket ] in sscanf

I want to scan lines like

"[25, 28] => 34"

I wrote a small program to test it out:

#include <cstdlib>
#include <iostream>

int main() {
        char* line = "[25, 28] => 34";
        char a1[100],  a2[100];
        int i;
        sscanf(line, "[%[^,], %[^\]] => %i", a1, a2, &i);
        std::cout << "a1 = " << a1 <<"\na2 = " << a2 << "\ni = "<<i <<"\n";
        return 0;
}

compiling this gives

warning: unknown escape sequence '\]'

and the output

a1 = 25
a2 = 28
i = -1073746244

If I change it to

sscanf(line, "[%[^,], %[^]] => %i", a1, a2, &i);

I get no compiler complaints but still

a1 = 25
a2 = 28
i = -1073746244

I know the problem is in the second token because

sscanf(line, "[%[^,], %[0123456789]] => %i", a1, a2, &i);

gives

a1 = 25
a2 = 28
i = 34

But I want to use a terminating condition for the second token. How do I do that?

like image 989
highBandWidth Avatar asked Apr 21 '11 22:04

highBandWidth


1 Answers

You want

sscanf(line, "[%[^,], %[^]]] => %i", a1, a2, &i);

Note the three consecutive ] characters -- the first is the character you don't want to match in the %[ set, the second ends the set starting with the %[ and the third matches the ] character in the input

like image 135
Chris Dodd Avatar answered Sep 18 '22 10:09

Chris Dodd