Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ copy std::string to char array with no null termination

I am writing to a binary file using a struct that just contains a char[32]. I basically need to format each block of data by performing various calculations on string arrays and concatenating the results. I am attempting to copy an std::string to a char array with no null termination. The more I read into this, the more confused I get. If I do:

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 the null terminator with c_str() makes the string length 33. If I subtract one char from the string, it works, but then I have the null terminator, which I don't want. I can successfully do the following:

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

but I want to construct the string first, since it often involves concatenating different strings from various arrays. For instance, I can do this with std::string:

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

but then I have the null terminator again. I'd just like to copy exactly the chars in the std::string with no null terminator.

I am using VC++ 6.0.

like image 317
Geo Ego Avatar asked Dec 01 '11 17:12

Geo Ego


3 Answers

You can't use strcpy because that looks for the NULL terminator to identify the end of the string, and copies the NULL to the output string.

Since you're going from a string to a char buffer, the simplest thing would be to use 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 );

And, by the way, you might be able to use a vector<char>, rather than a char data[32]

EDIT:

An aside: VC6 is an ancient compiler which was bad when it came out, terrible when the C++ Standard was ratified, and is completely unsupported by Microsoft. If something were to go wrong with it, they won't even talk to you. You should get off VC6 as soon as possible.

like image 72
John Dibling Avatar answered Sep 18 '22 12:09

John Dibling


Use memcpy instead of strcpy, that's what it's there for:

memcpy(blocks[0].data, buffer.data(), sizeof(blocks[0].data)); 
like image 25
Jon Avatar answered Sep 19 '22 12:09

Jon


Use strncpy() instead of strcpy():

strncpy(blocks[0].data, buffer.c_str(), 32); 
like image 36
Remy Lebeau Avatar answered Sep 18 '22 12:09

Remy Lebeau