C ++ copy std :: string to char array without null termination

I am writing to a binary using a structure containing only char [32]. I basically need to format each data block by doing various calculations on string arrays and concatenating the results. I am trying to copy std :: string array to char array without null termination. The more I read about it, the more I get embarrassed. If I do this:

struct block{
    char data[32];
};
block blocks[2048];
std::string buffer;

buffer = "12345678123456781234567812345678";
strcpy(blocks[0].data, buffer.c_str());

I get an error because adding a null terminator using c_str () makes the string length 33. If I subtract one of the char from the string, it works, but then I have a null terminator to want. I can do the following:

strcpy(blocks[0].data, "12345678123456781234567812345678");

but I want to build a string first, as it often involves combining multiple strings from different arrays. For example, I can do this with std :: string:

std::string buffer = stringArray1[0] + stringArray2[0];
strcpy(blocks[0].data, buffer.c_str());

but then again I have a zero limiter. I would just like to copy exactly the characters to std :: string without a null terminator.

I am using VC ++ 6.0.

+5
source share
4 answers

Use memcpyinstead strcpythat it is there for:

memcpy(blocks[0].data, buffer.data(), sizeof(blocks[0].data)); 
+10
source

You cannot use strcpyit because it searches for a NULL terminator to identify the end of the line and copies NULL to the output string.

Since you are moving from buffer stringto char, the easiest way to use is std::copy:

#include <algorithm>

static const size_t data_size = 32;
struct block{
    char data[data_size];
};

/* ... */

std::string buffer = stringArray1[0] + stringArray2[0];
std::copy( buffer.begin(), buffer.end(), blocks[0].data );

, , vector<char>, char data[32]

EDIT:

: VC6 - , , , , ++ Microsoft. - , . VC6.

+15

Use strncpy()instead strcpy():

strncpy(blocks[0].data, buffer.c_str(), 32); 
0
source

Use one of the lines below.

memcpy(blocks[0].data, buffer.c_str(), buffer.size());
memcpy(blocks[0].data, buffer.c_str(), 32);
memcpy(blocks[0].data, buffer.c_str(), buffer.size() > 32 ? 32 : buffer.size());
std::copy(buffer.begin(), buffer.end(), blocks[0].data).

By the way, do you handle the case when a string is shorter than 32 characters? Do you want to add a null byte?

-1
source

All Articles