Art3mis Art3mis - 6 days ago 5
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

scanf
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,
0020
will become
16
,
0030
will become
24
,
0100
will become
64
.

It seems to work with powers of
8
, and consider digits up to
8
(typing
0009
will cause it to print
0
and then
9
).

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

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.