yin yang
yin yang

Reputation: 229

Initializing char Buffer with a string in c++

I wan't to initialize a static char buffer with a string str in the code below but I am getting the following error :

error: cannot convert ‘std::string’ to >‘char’ in initialization

and if I use

static char buf[500] = str.c_str();

I get the following error:

error: invalid conversion from ‘const char*’ to ‘char*’

Below is my code :

std::string str = "<Version="+version+" Ret=\"false\"/>";
static char buf[500] = str;
int len=strlen(buf);
buf[len]='\0';
INFO("Static Buffer :: "<<buf);

Upvotes: 1

Views: 3646

Answers (2)

Weston McNamara
Weston McNamara

Reputation: 385

You can use std::string::copy().

std::string text = "Hello there!";
char* cStrText = new char[text.length()];

//Copy the string into the buffer
text.copy(cStrText, text.length(), 0);

Obviously, this performs a copy which may not be optimal. You might want to look into trying to move it.

https://www.cplusplus.com/reference/string/string/copy/

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

First of all, you cannot directly initialise a char[] from an std::string. It's just not possible. Even if you could, you would write = str, not = { str }.

So, you need to create the array first then assign the std::string's contents to it manually. Sadly, arrays are not assignable, so you're going to have to use an "algorithm" to do it.

Here we go:

const std::string str = "Hello world";
static char buf[500] = {};
std::copy(
   // from the start of the string
   std::begin(str),

   // to the end of the string, or to 499 chars in, whichever comes first
   std::begin(str) + std::min(str.size(), sizeof(buf)),

   // into buf
   std::begin(buf)
);

Yuck.

If you can, and this is likely the case, avoid it.

If you really need a C-string with the std::string's contents, just access str.c_str() whenever you need to. There is, in general, no need to keep a raw char array lying about, especially when you already have the right tool for the job doing that job.

Besides, as you are not initialising buf with that data, if it's function-static, this code probably does not have the intended effect.

Upvotes: 3

Related Questions