Can you use std::hex outside of a cin/cout <<

instead of
1
2
3
4
5
6
7
8
9
10
#include <iostream>
int g = 70;
cout << std::hex << g << "\n" ;

//instead like this

int h = 30;
int hex_num = std::hex(h);
cout << hex_num << "\n";
Last edited on
No. std::hex is a stream manipulator and is only used within the context of a stream.

What you can do is this:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
	const int h {30};
	std::ostringstream oss;

	oss << std::hex << h;
	std::cout << oss.str() << '\n';
}

Last edited on
int hex_num = std::hex(h);

This implies something more important: that you do not know what an 'int' actually IS.
an int is a group of bits, forming bytes, not a 'base 10 decimal text string' (which is what you see when you cout it). A number is a number: 0011 3 0x03 are all the same value, if you had 3 quarters, you still have 3 quarters, no matter how you write it. Cout is 'how you write it'. INT is how you work with it internally, without looking at it until you need to do so.
Topic archived. No new replies allowed.