I am relatively new to C++. Recent assignments have required that I convert a multitude of char buffers (from structures/sockets, etc.) to strings. I have been using variations on the following but they seem awkward. Is there a better way to do this kind of thing?
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
char* bufferToCString(char *buff, int buffSize, char *str)
{
memset(str, '\0', buffSize + 1);
return(strncpy(str, buff, buffSize));
}
string& bufferToString(char* buffer, int bufflen, string& str)
{
char temp[bufflen];
memset(temp, '\0', bufflen + 1);
strncpy(temp, buffer, bufflen);
return(str.assign(temp));
}
int main(int argc, char *argv[])
{
char buff[4] = {'a', 'b', 'c', 'd'};
char str[5];
string str2;
cout << bufferToCString(buff, sizeof(buff), str) << endl;
cout << bufferToString(buff, sizeof(buff), str2) << endl;
}
Given your input strings are not null terminated, you shouldn’t use str… functions. You also can’t use the popularly used
std::stringconstructors. However, you can use this constructor:std::string str(buffer, buflen): it takes achar*and a length. (actuallyconst char*and length)I would avoid the C string version. This would give:
If you really must use the
C-stringversion, either drop a0at thebufflenposition (if you can) or create a buffer ofbufflen+1, thenmemcpythe buffer into it, and drop a0at the end (bufflenposition).