user69514
user69514

Reputation: 27629

C++ convert int and string to 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

Upvotes: 7

Views: 5080

Answers (5)

Alexander Solonsky
Alexander Solonsky

Reputation: 11

those who write "const char* myString = "a number";" are just lousy programmers. Being not able to get the C basics - they rush into C++ and start speaking about the things they just don't understand.

"const char *" type is a pointer. "a number" - is array. You mix pointers and arrays. Yes, C++ compilers sometimes allow duct typing. But you must also understand - if you do duct typing not understanding where your "ductivity" is - all your program is just a duct tape.

Upvotes: 0

Jacob
Jacob

Reputation: 34621

#include <stdio.h>

char display_string[200];
sprintf(display_string,"%X\t%s",a,str.c_str());

I've used sprintf to format your number as a hexadecimal.

Upvotes: 2

Mike Marshall
Mike Marshall

Reputation: 7850

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());

Upvotes: 4

int3
int3

Reputation: 13201

str.c_str() will return a null-terminated C-string.

Note: not answering the main question since your comment indicated it wasn't necessary.

Upvotes: 1

CB Bailey
CB Bailey

Reputation: 793109

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

Upvotes: 20

Related Questions