Search code examples
c++integeroctal

Initializing integer with leading zeroes gives unexpected result (C++)


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?


Solution

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