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.

2
  • 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"? Commented Nov 19, 2020 at 13:39
  • That works! Wouldn't have thought that posix could be that easy sometimes, regarding the examples on the internet. Commented Nov 19, 2020 at 13:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.