JohnyBgood
JohnyBgood

Reputation: 67

using sscanf as number extractor didn't work properly when I put number first in a string

So, I saw this code somewhere which extracts numbers from given string.

while (1 == sscanf(s + total_n, "%*[^0123456789]%d%n", &i, &n))
    {
        total_n += n;
        answer +=i;
        printf("%d\n",i);
    }

so when I put "Monkey78hi9123" it gives

78
9123

This is what I expected and it works perfectly fine. However, when I put number first instead of alphabet

for example, "143Monkey3000" it prints nothing.

What I expected from this input is

143
3000

But I got just nothing.

I have no idea what makes this problem. Can anyone help?

Upvotes: 0

Views: 53

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126203

The format specifier %*[^0123456789] will match (and discard) one or more non-digit characters. So if the input string begins with a digit, it will fail to match, and scanf will immediately return 0.

Unfortunately there's no good way in scanf to match zero or more characters, so you end up needing multiple sscanf calls:

while (1 == sscanf(s + total_n, "%*[^0123456789]%d%n", &i, &n) ||
       1 == sscanf(s + total_n, "%d%n", &i, &n)) {

This works with sscanf because you can easily rescan the same string, but may not work so well wil fscanf. This is why you often need fgets+sscanf rather than fscanf.

Upvotes: 1

Related Questions