Problem summary
Assume that for some reason one tries to store the integer 31 as int num = 0031;
If I print out num
I get 25 instead. If I use cin
however, the number stored is indeed 31.
You can verify this by running the following code and type 0031 when prompted.
Code
#include <iostream>
using namespace std;
int main() {
cout << "Version 1\n========="<< endl;
{
int num = 0031;
cout << "Input was: " << num << endl;
}cout << "=========" << endl;
cout << "Version 2\n========="<< endl;
{
int num;
cout << "Insert num: ";
cin >> num;
cout << "Input was: " << num << endl;
}cout << "=========" << endl;
return 0;
}
Searching for the answer, I found this one Int with leading zeroes - unexpected result
Is it the same case in C ? Namely, integers with leading zeroes are stored as octal integers?
And why does the second block give the expected result? Is it because when using cin
the stream is stored as string and then the stoi()
function is implicitly used?
CodePudding user response:
For integer literals in C see eg here: https://en.cppreference.com/w/cpp/language/integer_literal. Yes, 0031
is an octal integer literal.
To get expected output from the second version of your code you can use the std::oct
io-manipulator:
int num;
cout << "Insert num: ";
cin >> std::oct >> num;
cout << "Input was: " << num << endl;
CodePudding user response:
This is becuase you are initializing num
with octal integer literal.whose value is 25 in decimal.
CodePudding user response:
if you convert 31 from octal system to decimal yo get 25 so you initialized your num in octal system
CodePudding user response:
You cannot use 0
as starting value in the integer variable. Because 0
is ignored in integer.