1

I have some confusions in my codes regarding std:: functions.

cout<<tmp;
cout<<std::hex<<setw(4)<<tmp;

tmp is an int variable. After setting tmp to hex type, when I print tmp again, it is not converted back to decimal type (In face I have to include std::dec). Can anyone explain for me what happened behind-the-scene?

Thanks in advance

  • 2
    Possible duplicate of [Restore the state of std::cout after manipulating it](https://stackoverflow.com/questions/2273330/restore-the-state-of-stdcout-after-manipulating-it) – Smit Ycyken Mar 19 '18 at 15:49
  • 1
    are those two lines swapped? otherwise I dont understand what is the problem – 463035818_is_not_an_ai Mar 19 '18 at 15:50
  • The code does not "[set] tmp to hex type"; it sets the **output stream** to write numerical values by converting them to a hexadecimal text representation. – Pete Becker Mar 19 '18 at 16:54

1 Answers1

5

std::hex is sticky. You'll need to use std::dec to change the settings so that subsequent integral numbers are displayed in decimal.

cout << std::hex << setw(4) << tmp;
cout << std::dec << setw(4) << tmp;
R Sahu
  • 204,454
  • 14
  • 159
  • 270