Zero at the beginning of int

I wonder when I saw errors like invalid digit in octal constant 9 and 8.Also it print wrong value for the value of "mobno"(in structure) if zero is the first digit, but it give error when zero is used as first digit for num at the end of program.Is there someone who would explain it for me?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
    using namespace std;
    int main()
    {
    	struct information
    	{
    		string  name;
    		string  bloodgroup;
    		int     mobno;
    	};
    	
    	information person1={"Ali Hamza","O-",434233434};
    	information person2={"Akram Ali","B",034};
    	cout << endl << person1.name << endl;
    	cout << person1.bloodgroup << endl << person1.mobno<< endl;
    	cout << endl << person2.name << endl << person2.bloodgroup << endl << person2.mobno<<endl;
    	
    	int num = 09;
    	cout << num;
    	
    	return 0;
    }

If a number (greater than 7) begins with 0, then the compiler treats it as octal which is 8-based, which you don't want.

So in your line 18, set num = 9 instead of 09.
int num = 9;
If a number (greater than 7) begins with 0, ...

It also treats numbers 7 and under as octal; it's just that they're in step with decimals.

From the Literals / Integer Numerals subsection of:

Constants
http://www.cplusplus.com/doc/tutorial/constants/

<quote>

In addition to decimal numbers (those that most of us use every day), C++ allows the use of octal numbers (base 8) and hexadecimal numbers (base 16) as literal constants. For octal literals, the digits are preceded with a 0 (zero) character. And for hexadecimal, they are preceded by the characters 0x (zero, x). For example, the following literal constants are all equivalent to each other:

1
2
3
75         // decimal
0113       // octal
0x4b       // hexadecimal   


</quote>

Edit: add C++ Shell friendly example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

int main() {
    int a = 75;    // decimal
    int b = 0113;  // octal
    int c = 0x4b;  // hexadecimal

    cout << showbase; // tell cout to show 0- for octal and 0x- for haxadecimal

    cout << "[dec]\n" << dec
         << "a = " << a << "\n"
         << "b = " << b << "\n"
         << "c = " << c << "\n"
         << "\n";

    cout << "[hex]\n" << hex
         << "a = " << a << "\n"
         << "b = " << b << "\n"
         << "c = " << c << "\n"
         << "\n";

    cout << "[oct]\n" << oct
         << "a = " << a << "\n"
         << "b = " << b << "\n"
         << "c = " << c << "\n"
         << "\n";

    return 0;
}


Andy

PS And line 13 of code in opening post is also suspect.
Last edited on
Thankyou very much @andywestken.
Topic archived. No new replies allowed.