Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ illegal digit, simple issue

Tags:

c++

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?

like image 704
Overseer10 Avatar asked Jan 24 '11 04:01

Overseer10


4 Answers

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

like image 92
AndersK Avatar answered Oct 03 '22 23:10

AndersK


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...

like image 23
xaxxon Avatar answered Oct 04 '22 00:10

xaxxon


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.

like image 38
Jeremy Friesner Avatar answered Oct 03 '22 22:10

Jeremy Friesner


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;
like image 39
Benjamin Lindley Avatar answered Oct 03 '22 23:10

Benjamin Lindley