Overseer10
Overseer10

Reputation: 361

C++ illegal digit, simple issue

I'm running against this error:

int temp = 0789;

error C2041: illegal digit '8' for base '8'

For what I can understand is that the compiler understands any number that begins with 0 like 0123 to be octal. But how can I tell the compiler to just take it with the 0 in front?

Upvotes: 5

Views: 5910

Answers (4)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

If you want to display your number with a zero in front of it, just do this:

int temp = 789;
std::cout << '0' << temp;

If you want to pad any arbitrary number with zeroes so that it's 4 digits, then you can do this(being sure to include <iomanip>)

int temp = 789;
std::cout << std::setw(4) << std::setfill('0') << temp;

Upvotes: 1

xaxxon
xaxxon

Reputation: 19761

http://msdn.microsoft.com/en-us/library/00a1awxf(v=vs.80).aspx

Great resource about this.

0xff is hex 0123 is octal 123u is unsigned ..lots more...

Upvotes: 4

Jeremy Friesner
Jeremy Friesner

Reputation: 73061

Putting a 0 at the front of the number tells the compiler that the value is expressed in octal; octal digits are only 0 through 7, so '789' is not a valid octal number. The only solution here is to remove the 0 from the beginning of the number (assuming you meant to have the number be in decimal).... or provide a valid octal number (if you really meant to use octal).

Well, I suppose you could do this:

int temp = atoi("0789");  

But that will be rather inefficient, since the value will be computed from the string at run-time, rather than compiled in directly.

Upvotes: 2

AndersK
AndersK

Reputation: 36082

If you put 0 in front it believes its an octal value, thus 8 and 9 are illegal digits.

Upvotes: 6

Related Questions