Daniele Daniele - 2 months ago 22
C++ Question

copy first n chars to an std::string

I have a char pointer that points to a buffer of unknown length:

char* buffer;

I need to copy the first N (N is an input variable) chars to an std::string if N !=0.
My current code is:

int N = <something>;
std::string text;
if (N != 0)
text.assign(buffer, N);

the thing I do not like, is that when the size of buffer is less than N, the resulting size of text is N.

Is there any function in the standard library to copy the first N chars of buffer to text without forcing the size of text to N?

i.e if buffer is only 1 char and N = 100, I want that text.size() = 1

Is a custom copy, byte by byte, the solution?


You can use memchr to look for the zero byte, and limit the search to N bytes:

size_t N = ...;
char* pos = memchr(buffer, '\0', N);
text.assign(buffer, pos ? pos - buffer : N);

If the byte is not found, the length of the output string should be N. If it's found, then memstr returns the pointer to it. Subtracting the original pointer will yield the desired length.

This doesn't handle the case of N = 0 in any special manner - that is, if N is 0, the output will be empty. If you want other behavior, make a special-case for it.