Using C++ hex and cin

China☆狼群 提交于 2019-12-06 04:50:38

问题


If you have the following code:

cout << hex << 10;

The output is 'a', which means the decimal 10 is converted into its hexadecimal value.

However, in the code below...

int n;
cin >> hex >> n;
cout << n << endl;

When input is 12, the output becomes 18. Can anyone explain the details of the conversion? How did it became a decimal value?

I'm interested in the point where it became an int. If broken down, it would be:

(( cin >> hex ) >> n);

Is this correct?


回答1:


The hex manipulator only controls how a value is read - it is always stored using the same internal binary representation. There is no way for a variable to "remember" that it was input in hex.




回答2:


"12" in hex is "18" in decimal. When you put in "12" into a hex cin stream, the internal value is 18 decimal. When you output to a stream which is by default decimal, you see the decimal value - "18".




回答3:


It reads 0x12 (a hex value) and stores it in n, which you then print in decimal. Variables simply contain values, they do not contain information about the base (actually they store everything in base 2).



来源:https://stackoverflow.com/questions/2387386/using-c-hex-and-cin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!