Manipulator how it works ?

Hello,

I am beginner in C++ and I am trying to understand some features.

1 At first, I do not really understand how to use manipulators...

For example, if I have an integer (=286286), and I want to convert this value in hex or oct format, I can use the following code:

1
2
3
4
5
6
7
8
#include <iostream>     // std::cout, std::dec, std::hex, std::oct

int main () {
  int n = 286286;
  std::cout << std::hex << n << '\n';
  std::cout << std::oct << n << '\n';
  return 0;
}


Great it has converted, the result is displayed in the console, but in fact it seems to be useless if only done like this...

What if I want to use the results for further treatment in the program?
How to say in C++ language "resultConversion=hex(Integer)"?

2 Why does the definition in the reference tab, it is mentioned "ios_base& hex (ios_base& str);" ? Why mention this while we type "std::cout << std::dec << n"?

Thanks for those will spend a little time to explain.
1
2
3
4
5
6
std::string IntToStr( const int num )
{
	std::stringstream ss;
	ss << num;
	return ss.str( );
}

To convert to hexadecimal, use std::stoi.
http://www.cplusplus.com/reference/string/stoi/
I want to convert this value in hex or oct format

The manipulator does not convert the object from decimal to hex.
The manipulator does display the object as hex.
It is "manipulating" the output stream, not the object being output.

You can however capitalise on this to store your decimal number as a hexadecimal string. This principle is illustrated by @integralfx above, but to be more specific:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <sstream>

std::string dec_to_hex(long int dec_val)
{
	std::stringstream hex_str;
	hex_str << std::hex << dec_val;
	return (hex_str.str());
}

int main()
{
	std::cout << dec_to_hex(324) << std::endl;
	std::string my_hex = dec_to_hex(792);
	std::cout << my_hex << std::endl;
	
	return (0);
}

"ios_base& hex (ios_base& str);

The manipulator (std::hex) is a function that takes a reference to a stream, manipulates the stream, and returns a reference to the manipulated stream.

Unlike normal functions that you call by passing arguments in parantheses (e.g. putchar('c');), It is designed to be used alone, with no arguments, with the << and >> operators. It can be called with an expression such as cout << std::hex for any out of type std::basic_ostream or with an expression such as cin >> std::hex for any in of type std::basic_istream
Hello,

Okie got it for those points.

Thank you @integralfx and @tipaye to have taken some time.
Topic archived. No new replies allowed.