我对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;
}
问题是缓冲区没有终止空值。 – 2009-05-22 02:20:22
使用常量字符串初始化char数组时,它会得到一个终止的空值。当你使用string :: c_str()时,你也会得到一个终止的null。我不明白你的投诉是什么。 – 2009-05-22 02:27:56
答案中的代码是正确的,但与问题不同。 “char buff [4] = {'a','b','c','d'};”不会给你一个以null结尾的字符串。 – markh44 2009-05-22 08:02:32