how to pass some data to string

Assume, I need to pass some data to buffer for future copy to terminal or so on.
How can I proceed?
I know only stupid way with WinAPI (VK_CONTROL)
Looking for native way, C+11

Are you asking how to convert data to a string? It depends on the data...

For integers you might want to use std::to_string but for other types, and to get more control over how it's formatted, you might want to use std::ostringstream.

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

int main()
{
	int num = 123;
	std::string str = std::to_string(num);
	std::cout << str << "\n";
	
	std::ostringstream oss;
	oss << "Hello! " << std::setw(5) << std::setfill('0') << num; // write to it the same way as with std::cout
	std::string str2 = oss.str(); // extract string
	std::cout << str2 << "\n";
}
123
Hello! 00123
Last edited on
VK_CONTROL is Windows Virtual Key code for the CTRL key. How are you using that and what in detail are you trying to achieve?
if its for display later, maybe a stringstream and treat it just like cout, then when you need it, its there.
that will do the same auto conversion/formatting that cout would do with the same output manipulations.
The WinAPI virtual key codes are #defines, they are representations of hex numbers.

https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes

Converting a number, even a hex number, to a string is doable. C++20 has formatting library if you want to preserve the value as hex. std::format is one way.

https://en.cppreference.com/w/cpp/utility/format/format

Your question is rather ambiguous, you should explain in greater detail exactly what you are trying to do.

George P wrote:
The WinAPI virtual key codes are #defines, they are representations of hex numbers.

You make it sound like "hex numbers" are some special type of number. Hex(adecimal) is just an alternative way to write numbers. 0x11 and 17 represent the same value in C++. Once you store them in a variable you won't be able to tell them apart.

George P wrote:
Converting a number, even a hex number, to a string is doable.

"hex" is rather a property of the string (the textual representation of the number) than the number itself. A number is just a number, it doesn't contain information about how it should be displayed. It's when you print it or convert it to string that you got to choose if you want to use the default decimal notation (base 10), hexadecimal (base 16), binary (base 2) or the more uncommon octal (base 8). Other notations (e.g. quinary, base 5) are of course also possible but then you can not expect much help from the standard library.
Last edited on
Topic archived. No new replies allowed.