将char数组缓冲区转换为字符串的好方法?

时间:2021-12-11 16:04:07

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?

我对C ++比较陌生。最近的任务要求我将大量的char缓冲区(从结构/套接字等)转换为字符串。我一直在使用以下的变体,但它们似乎很尴尬。有没有更好的方法来做这种事情?

#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;

}

7 个解决方案

#1


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:

鉴于您的输入字符串不是以null结尾,您不应该使用str ...函数。您也不能使用常用的std :: string构造函数。但是,您可以使用此构造函数:

std::string str(buffer, buflen): it takes a char* and a length. (actually const char* and length)

std :: string str(buffer,buflen):它需要一个char *和一个长度。 (实际上是const char *和长度)

I would avoid the C string version. This would give:

我会避免使用C字符串版本。这会给:

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).

如果你真的必须使用C字符串版本,要么在bufflen位置删除0(如果可以)或者创建bufflen + 1的缓冲区,然后将缓冲区memcpy到其中,并在结尾处放下0(bufflen位置) )。

#2


If the data buffer may have null ('\0') characters in it, you don't want to use the null-terminated operations.

如果数据缓冲区中可能包含空('\ 0')字符,则不希望使用以null结尾的操作。

You can either use the constructor that takes char*, length.

您可以使用带有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(buff)构造函数与上面的buff []数组一起使用,因为它不是以null结尾的。

#3


std::string to const char*:

std :: string到const char *:

  my_str.c_str();

char* to std::string:

char *到std :: string:

  string my_str1 ("test");
  char test[] = "test";
  string my_str2 (test);

or even

  string my_str3 = "test";

#4


std::string buf2str(const char* buffer)
{
    return std::string(buffer);
}

Or just

std::string mystring(buffer);

#5


The method needs to know the size of the string. You have to either:

该方法需要知道字符串的大小。你必须:

  1. in case of char* pass the length to method
  2. 在char *的情况下将长度传递给方法

  3. in case of char* pointing to null terminating array of characters you can use everything up to null character
  4. 如果char *指向null终止字符数组,则可以使用最多为null字符的所有内容

  5. for char[] you can use templates to figure out the size of the char[]
  6. 对于char [],您可以使用模板来计算char []的大小

1) example - for cases where you're passing the bufflen:

1)示例 - 对于您传递bufflen的情况:

std::string bufferToString(char* buffer, int bufflen)
{
    return std::string(buffer, bufflen);
}

2) example - for cases where buffer is points to null terminated array of characters:

2)示例 - 对于缓冲区指向null终止字符数组的情况:

std::string bufferToString(char* buffer)
{
    return std::string(buffer);
}

3) example - for cases where you pass char[]:

3)示例 - 对于传递char []的情况:

template <typename T, size_t N>
std::string tostr(T (&array)[N])
{
    return std::string(array, N);
}


Usage:
char tstr[] = "Test String";
std::string res = tostr(tstr);
std::cout << res << std::endl;

For the first 2 cases you don't actually have to create new method:

对于前两种情况,您实际上不必创建新方法:

 std::string(buffer, bufflen);
 std::string(buffer);

#6


Use string constructor that takes the size:

使用带有大小的字符串构造函数:

string ( const char * s, size_t n );

Content is initialized to a copy of the string formed by the first n characters in the array of characters pointed by s.

内容初始化为由s指向的字符数组中的前n个字符形成的字符串的副本。

cout << std::string(buff, sizeof(buff)) << endl;

http://www.cplusplus.com/reference/string/string/string/

Non-null-terminated buffer to C string:

非空终止缓冲区到C字符串:

memcpy(str, buff, buffSize);
str[bufSize] = 0; // not buffSize+1, because C indexes are 0-based.

#7


string value (reinterpret_cast(buffer), length);

字符串值(reinterpret_cast(缓冲区),长度);

#1


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:

鉴于您的输入字符串不是以null结尾,您不应该使用str ...函数。您也不能使用常用的std :: string构造函数。但是,您可以使用此构造函数:

std::string str(buffer, buflen): it takes a char* and a length. (actually const char* and length)

std :: string str(buffer,buflen):它需要一个char *和一个长度。 (实际上是const char *和长度)

I would avoid the C string version. This would give:

我会避免使用C字符串版本。这会给:

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).

如果你真的必须使用C字符串版本,要么在bufflen位置删除0(如果可以)或者创建bufflen + 1的缓冲区,然后将缓冲区memcpy到其中,并在结尾处放下0(bufflen位置) )。

#2


If the data buffer may have null ('\0') characters in it, you don't want to use the null-terminated operations.

如果数据缓冲区中可能包含空('\ 0')字符,则不希望使用以null结尾的操作。

You can either use the constructor that takes char*, length.

您可以使用带有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(buff)构造函数与上面的buff []数组一起使用,因为它不是以null结尾的。

#3


std::string to const char*:

std :: string到const char *:

  my_str.c_str();

char* to std::string:

char *到std :: string:

  string my_str1 ("test");
  char test[] = "test";
  string my_str2 (test);

or even

  string my_str3 = "test";

#4


std::string buf2str(const char* buffer)
{
    return std::string(buffer);
}

Or just

std::string mystring(buffer);

#5


The method needs to know the size of the string. You have to either:

该方法需要知道字符串的大小。你必须:

  1. in case of char* pass the length to method
  2. 在char *的情况下将长度传递给方法

  3. in case of char* pointing to null terminating array of characters you can use everything up to null character
  4. 如果char *指向null终止字符数组,则可以使用最多为null字符的所有内容

  5. for char[] you can use templates to figure out the size of the char[]
  6. 对于char [],您可以使用模板来计算char []的大小

1) example - for cases where you're passing the bufflen:

1)示例 - 对于您传递bufflen的情况:

std::string bufferToString(char* buffer, int bufflen)
{
    return std::string(buffer, bufflen);
}

2) example - for cases where buffer is points to null terminated array of characters:

2)示例 - 对于缓冲区指向null终止字符数组的情况:

std::string bufferToString(char* buffer)
{
    return std::string(buffer);
}

3) example - for cases where you pass char[]:

3)示例 - 对于传递char []的情况:

template <typename T, size_t N>
std::string tostr(T (&array)[N])
{
    return std::string(array, N);
}


Usage:
char tstr[] = "Test String";
std::string res = tostr(tstr);
std::cout << res << std::endl;

For the first 2 cases you don't actually have to create new method:

对于前两种情况,您实际上不必创建新方法:

 std::string(buffer, bufflen);
 std::string(buffer);

#6


Use string constructor that takes the size:

使用带有大小的字符串构造函数:

string ( const char * s, size_t n );

Content is initialized to a copy of the string formed by the first n characters in the array of characters pointed by s.

内容初始化为由s指向的字符数组中的前n个字符形成的字符串的副本。

cout << std::string(buff, sizeof(buff)) << endl;

http://www.cplusplus.com/reference/string/string/string/

Non-null-terminated buffer to C string:

非空终止缓冲区到C字符串:

memcpy(str, buff, buffSize);
str[bufSize] = 0; // not buffSize+1, because C indexes are 0-based.

#7


string value (reinterpret_cast(buffer), length);

字符串值(reinterpret_cast(缓冲区),长度);