This is a little hard I can't figure it out.
I have an int and a string that I need to store it as a char*, the int must be in hex
i.e.
int a = 31;
string str = "a number";
I need to put both separate by a tab into a char*.
Output should be like this:
1F a number
In this C program, we are reading the number using 'num' variable. The tostring() function is used to convert an integer to string & vice-versa. Using tostring() function convert an integer to string. Assign the value of 'num' variable to 'n' variable.
To convert the int to char in C language, we will use the following 2 approaches: Using typecasting. Using sprintf()
The itoa() function coverts the integer n into a character string. The string is placed in the buffer passed, which must be large enough to hold the output. The radix values can be OCTAL, DECIMAL, or HEX.
Method 1: Using toString Method of Integer Class The Integer class has a static method that returns a String object representing the specified int parameter. The argument is converted and returned as a string instance. If the number is negative, the sign will be preserved.
With appropriate includes:
#include <sstream>
#include <ostream>
#include <iomanip>
Something like this:
std::ostringstream oss;
oss << std::hex << a << '\t' << str << '\n';
Copy the result from:
oss.str().c_str()
Note that the result of c_str
is a temporary(!) const char*
so if your function takes char *
you will need to allocate a mutable copy somewhere. (Perhaps copy it to a std::vector<char>
.)
Try this:
int myInt = 31;
const char* myString = "a number";
std::string stdString = "a number";
char myString[100];
// from const char*
sprintf(myString, "%x\t%s", myInt, myString);
// from std::string :)
sprintf(myString, "%x\t%s", myInt, stdString.c_str());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With