C ++ illegal number, simple problem

I am running against this error:

int temp = 0789; error C2041: illegal digit '8' for base '8' 

I understand that the compiler understands any number starting with 0, like 0123, to be octal. But how can I tell the compiler to just take it from 0 in front?

+4
source share
4 answers

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

Great resource about this.

0xff - hex 0123 - octal 123u unsigned .. more ...

+3
source

If you put 0 in front, he thinks that its octal value, so 8 and 9 are illegal numbers.

+4
source

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

Well, I suppose you could do this:

 int temp = atoi("0789"); 

But this will be quite inefficient, as the value will be computed from the string at run time, and not compiled directly.

+2
source

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

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

If you want to fill any arbitrary number with zeros so that it is 4 digits, you can do this (be sure to include <iomanip> )

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

Source: https://habr.com/ru/post/1336737/


All Articles