By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,435 Members | 1,372 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,435 IT Pros & Developers. It's quick & easy.

scanf %u

P: n/a

unsigned int number;
scan=sscanf(" -76","%u",&number);
printf("number has the value %d as %%d and %u as %%u.\n",number,number);

under gcc/3.2.2* this is returning 1, and assigning a value to number.
Isn't this wrong?

My reading of the man pages is that a '-' is not allowed. Doesn't this mean
it should be impossible to make the conversion, scanf should return 0 and
number should be left alone - just like if another non allowed character
were there, (eg: a letter)?

What have I missed?

* gcc (GCC) 3.2.2 (Mandrake Linux 9.1 3.2.2-3mdk)

Nov 13 '05 #1
Share this Question
Share on Google+
2 Replies

P: n/a
On Sat, 05 Jul 2003 13:32:39 +0100, viza <no**@foo.invalid> wrote:

unsigned int number;
scan=sscanf(" -76","%u",&number);

under gcc/3.2.2* this is returning 1, and assigning a value to number.
Isn't this wrong?
Nope, the C99 standard has this to say about the %u specifier ( #12)

| u Matches an optionally signed decimal integer, whose format is the same as
| expected for the subject sequence of the strtoul function with the value 10
| for the base argument. The corresponding argument shall be a pointer to
| unsigned integer.

Notice "optionally signed". Then we need to look at the definition of
strtoul ( #5) to see how it treats negative numbers

| If the subject sequence begins with a minus sign, the value resulting from
| the conversion is negated (in the return type).

strtoul's return type is unsigned long, so in this case -(unsigned long)76
would be returned.

There appears to be a weakness in the specification at this point though, as
it is not specified *scanf converts that unsigned long value to unsigned
int. The natural way would be "as if by assignment", giving
(unsigned int)-(unsigned long)76, but this is not specified anywhere AFAICT.
printf("number has the value %d as %%d and %u as %%u.\n",number,number);

This line has undefined behaviour, because the first conversion specifier
(%d) does not match the type of ''number''.

-- Mat.

Nov 13 '05 #2

P: n/a
and then viza said:

Thanks Mathew. My pooey server doesn't have your post, but I got it
eventualy through google.
Nov 13 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.