Search code examples
c++hexiostreamnumericoctal

why this C++ program gives incorrect output?


Consider following program:

#include <iostream>
int main()
{
    std::cout<<std::ios::showbase<<123<<", "<<std::hex<<123<<", "<<std::oct<<123<<'\n';
}

Expected Output: 123, 0x7b, 0173

Acquired Output: 512123, 7b, 173 (see live demo here: http://ideone.com/Khzj5j )

But If I modify the above program slightly as following:

#include <iostream>
using namespace std;
int main()
{
    cout<<showbase<<123<<", "<<hex<<123<<", "<<oct<<123<<'\n';
}

Now I got desired output. (see live demo here http://ideone.com/gcuHbm ).

Why first program gave incorrect output but 2nd program doesn't? What's going wrong in first program?


Solution

  • std::ios::showbase is a format flag. std::showbase is a function that takes a std::ios_base and calls ios_base::setf(std::ios::showbase) on it to set the showbase flag.

    You use the prior in your first example and the latter in your second example.