开发者

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?


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


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


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜