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;
}
Using StringBuilderCreate a StringBuilder object. Loop through the character array and append each character to the StringBuilder object using the built-in append() method. Convert the StringBuilder object to a String using the toString() method.
We can convert a char to a string object in java by using the Character. toString() method.
So the character array approach remains significantly faster although less so.
Given your input strings are not null terminated, you shouldn't use str... functions. You also can't use the popularly used std::string
constructors. However, you can use this constructor:
std::string str(buffer, buflen)
: it takes a char*
and a length. (actually const char*
and length)
I would avoid the C string version. This would give:
std::string bufferToString(char* buffer, int bufflen)
{
std::string ret(buffer, bufflen);
return ret;
}
If you really must use the C-string
version, either drop a 0
at the bufflen
position (if you can) or create a buffer of bufflen+1
, then memcpy
the buffer into it, and drop a 0
at the end (bufflen
position).
If the data buffer may have null ('\0') characters in it, you don't want to use the null-terminated operations.
You can either use the constructor that takes char*, length.
char buff[4] = {'a', 'b', 'c', 'd'};
cout << std::string(&buff[0], 4);
Or you can use the constructor that takes a range:
cout << std::string(&buff[0], &buff[4]); // end is last plus one
Do NOT use the std::string(buff) constructor with the buff[] array above, because it is not null-terminated.
std::string to const char*:
my_str.c_str();
char* to std::string:
string my_str1 ("test");
char test[] = "test";
string my_str2 (test);
or even
string my_str3 = "test";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With