Search code examples
c++stringpointerscharmemcpy

Best way to add a char prefix to a char* in C++?


I need to add a prefix ('X') to the char* (" is cool").

What is the BEST way to do this?

What is the easiest way?

char a = 'X';
char* b= " is cool";

I need:

char* c = "X is cool";

So far I tried strcpy-strcat, memcpy;

I'm aware this sounds as a stupid, unresearched question. What I was wondering is whether there is a way to add the char to the array without turning the char into a string.


Solution

  • How about using C++ standard library instead of C library functions?

    auto a = 'X';
    auto b = std::string{" is cool"};
    b = a+b;
    

    or short:

    auto a ='X';
    auto b = a+std::string{" is cool"};
    

    note that the explicit cast to string is mandatory.