Exit from the square bracket] in sscanf
I want to scan strings like
"[25, 28] => 34" I wrote a small program to test it:
#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; } compilation gives
warning: unknown escape sequence '\]' and exit
a1 = 25 a2 = 28 i = -1073746244 If I change it to
sscanf(line, "[%[^,], %[^]] => %i", a1, a2, &i); I do not receive compiler complaints, but still
a1 = 25 a2 = 28 i = -1073746244 I know that 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 the termination condition for the second token. How to do it?
As others have said ... I'm not quite sure what you want to do here ...
Assuming things between brackets are always integers, you can simply do:
int a, b, c; sscanf(line, "[%d, %d] => %d", &a,&b,&c); If you really insist on using regular expressions and want some kind of common material to go between the brackets, then you are looking for:
sscanf(line, "[%[^,], %[^]]] => %d", a1, a2, &i); the second regular expression must match all characters except ] at the end. I believe that you previously tried to avoid ] , but this is not necessary, and the compiler throws an error because it does not know how to handle this escape.
In the capture clause for a2 there is 3 ] , because the first says: โdo not include this character in the set of matches of charactersโ, the second closes the set of matches of characters, and the third matches ] in the input [25, 28] => 34 .
If I completely misunderstood your question, Iโll just clarify, and I can reconsider.
It looks like your question basically boils down to "how to include the character ] in scanf scan". It is possible, and you do not need to avoid it. In particular, for this purpose, the language specification states that when the character ] immediately follows the opening character [ or immediately follows the opening character ^ , which ] is considered part of the scan, not a closing bracket. So, in your case, the format specifier should look like "[%[^,], %[^]]] => %i" . No \ .
I see that you understood almost correctly, except that after the second scan you forgot the third character ] .
Sounds to me like a compiler error (or, in fact, a library) (although you need a third right key, not just two). According to the standard (C99, ยง7.19.6.2):
If the conversion specifier begins with [] or [^], the right bracket symbol is in the scan list, and the next next right bracket symbol is the corresponding right bracket that ends the specification;