1

A newbie in C is trying to extract two numbers from a string using sscanf(). The numbers shall be parsed from strings formatted like "7-12", which should result in firstNode = 7and secondNode = 12. So I want to get the numbers, the minus sign can be understood as a number seperator. My current implementation is similar to the example I found on this SO answer:

void extractEdge(char *string) {
    int firstNode = 123;
    int secondNode = 123;

    sscanf(string, "%*[^0123456789]%u%*[^0123456789]%u", &firstNode, &secondNode);
    printf("Edge parsing results: Arguments are %s, %d, %d", string, firstNode, secondNode);
}

But if I execute the code above, there always is retourned the inital value 123 for both ints. Note that the output of string gives the correct input String, so I think an invalid string can't be a probable cause for this problem.

Any ideas why the code is not working? Thanks in advance for your help.

BenjyTec
  • 1,719
  • 2
  • 12
  • 22
  • 4
    `%*[^0123456789]` has to match _at least one_ character. If your string starts with `7`, that means `%*[]` fails, and makes `sscanf` return. Why not just `scanf("%d-%d"`? – KamilCuk Nov 19 '20 at 13:39
  • That works! Wouldn't have thought that posix could be that easy sometimes, regarding the examples on the internet. – BenjyTec Nov 19 '20 at 13:51

1 Answers1

1

%*[^0123456789] requires one or more non-digit character, but the first character of you input 7-12 is a digit. This makes sscanf() stop there and read nothing.

Remove that and use "%d%*[^0123456789]%d" as format specifier to deal with 7-12.

Also note that correct format specifier for reading decimal int is %d, not %u. %u is for reading unsigned int.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70