Art3mis Art3mis - 1 year ago 65
C++ Question

Scanf reads wrong integer when 0 in front

This is my first question, so forgive me if I get something wrong.
I am very new to programming, and I came across a problem I can't find a solution to online. When using

for an integer, if my imput starts with one or two zeros, in some cases it will read it in some other system (not even binary).
For example,
will become
will become
will become

It seems to work with powers of
, and consider digits up to
will cause it to print
and then

There might be a simple rule I'm not aware of, I'm sorry if the answer is obvious. Thanks in advance for anyone who answers!

Answer Source

There are different notations for the popular bases (base 8, 10 and 16).

Base 8: Also known as Octal. You define a number as base 8 when you put a 0 in front of the input number. So when you input 020, it is read as 16in decimal.

Base 10: Also known as Decimal. You just write a number you want to input without any leading 0s. So when you input 20, it is read as 20.

Base 16: Also known as Hexadecimal. You write it with an 0x in the front. So inputting 0x20, it will be stored as 32 in decimal.

If you are reading the number using scanf() with format specifier as %d %i, then it is reading an octal number and interpreting it as an integer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download