Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ convert int and string to char*

Tags:

c++

string

char

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
like image 528
user69514 Avatar asked Nov 19 '09 20:11

user69514


People also ask

Can we convert int to string in C?

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.

Can we convert int to char in C?

To convert the int to char in C language, we will use the following 2 approaches: Using typecasting. Using sprintf()

What does itoa do in C?

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.

Can we store integer in string?

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.


2 Answers

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>.)

like image 112
CB Bailey Avatar answered Oct 01 '22 15:10

CB Bailey


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());
like image 24
Mike Marshall Avatar answered Oct 01 '22 17:10

Mike Marshall