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 numb开发者_Go百科er
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());
#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.
str.c_str()
will return a null-terminated C-string.
Note: not answering the main question since your comment indicated it wasn't necessary.
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.
精彩评论