C++ convert int and string to char*

2019-01-20 09:18发布

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

标签: c++ string char
5条回答
Viruses.
2楼-- · 2019-01-20 10:00

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());
查看更多
对你真心纯属浪费
3楼-- · 2019-01-20 10:02

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

查看更多
forever°为你锁心
4楼-- · 2019-01-20 10:02

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

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

查看更多
Summer. ? 凉城
5楼-- · 2019-01-20 10:04
#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.

查看更多
再贱就再见
6楼-- · 2019-01-20 10: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.

查看更多
登录 后发表回答