user3072005
user3072005

Reputation: 3

Separated integers with comma delimiters and sscanf

I need help with sscanf. I have a data file. I read it line by line. One line is look like this: 23,13,45;

I want to read the integers. I try this code:

unsigned char a,b,c;
sscanf(line,"%d,%d,%d;",&a,&b,&c);

But this is not working, only the first number read, the others is 0.

Upvotes: 0

Views: 1019

Answers (2)

Michał Trybus
Michał Trybus

Reputation: 11794

This is because %d expects a pointer to a 4-byte integer, and you are passing a pointer to a 1-byte char. Because variables a, b and c are stored in the order of decreasing memory addresses, sscanf first fills a with 23, at the same time filling 3 other bytes of stack memory with zeros (this is a memory violation, BTW). Then it fills b with 13, also filling a and two other bytes with zeros. In the end it fills c with 45, also filling a and b and one other byte with zeros. This way you end up with zeros in both b and a, and an expected value only in c.

Of course this is only one possible scenario of what can happen, as it depends on the architecture and compiler.

A proper way to read 4 integers would be to use int instead of unsigned char, or change the format specifier.

Upvotes: 1

P.P
P.P

Reputation: 121387

Correct format specifier for unsigned char is %hhu.

Other than that I don't see any problem as long as line does contain the string in the format you expect.

Upvotes: 1

Related Questions