简体   繁体   中英

how to understand the default format of cout

I hope this is not a naive question. Is type conversion performed implicitly in c++? Because I have asked user to input a number in hexadecimal format, and then when i output that number to the screen without mentioning its format, it is displayed as a decimal format. Am I missing something here?

#include <iostream>
#include <iomanip> using namespace std; 

int main() { int number = 0; 
             cout << "\nEnter a hexadecimal number: " << endl; 
              cin >> hex >> number;
            cout << "Your decimal input: " << number << endl; number; 
                }

There's no type conversion between hexadecimal and decimal here. Internally your number will be stored in two's complimentary (a binary representation) no matter whether it has been read in as a hex or decimal number. Converting from a string of dec/hex to an integer and the other way around happens when the number is inputted/outputted.

With std::hex you tell the stream you tell the stream to change its default numeric base for integer I/O. Without it, the default is decimal. So if you only do it for std::cin , then it is reading in numbers as hex, but std::cout is still outputting decimal numbers. If you want it to also change its base to hexadecimal, you have to do the same with std::cout :

std::cout << std::hex << "Your hexadecimal input: " << number << std::endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM