MarkSteve
MarkSteve

Reputation: 35

"Minus" not being captured

Running:

#include <stdio.h>

int main(int argc, char *argv[]) {
    const char *exp = "10-2+3*5";
    char tok[255];
    sscanf(exp, "%[^+-*/^]", tok);
    printf("%s\n", tok);
    sscanf(exp, "%[^-+*/^]", tok);
    printf("%s\n", tok);
    return 0;
}

Would output:

10-2
10

But why?

Upvotes: 0

Views: 149

Answers (1)

Stef
Stef

Reputation: 6981

Put the hyphen at the end of your [...] set. This is similar to regular expressions.

sscanf's %[...] format accepts ranges. A range could be used like this: %[a-z]

In order to distinguish matching a plain hyphen, you must put it at the end, so it is not interpreted as a range.

You can find more documentation on the sscanf manual page. Scroll down to the section where the [ pattern is described.

Upvotes: 2

Related Questions