这个隐含两个细节:
uc没有'\0'结尾,因此冒然当字符串赋值给string或CString,在正常字符串后面要出乱码(不知道如何结尾)
这是unsigned 字符数组,和一般的char array =>string不同,需要强制类型转换。
方法很多,如下列举3种:【我用的GCC编译器, 用string演示;VC的CString方法相同】
#include
#include
#include
#include
#include
using namespace std;
int main(int argc, char** argv) {
unsigned char uc[3] = {0x31,0x32,0x33};
char *pch;
size_t len = sizeof(uc) / sizeof(uc[0]);
string str1 (reinterpret_cast(uc),len); //方法1
string str2;
string str3;
//方法2
pch = new char[len+1];
memcpy(pch, uc, len);
pch[len] = '\0';
str2 = pch;
delete pch;
//方法3
stringstream ss;
copy(uc, uc+len, ostream_iterator(ss));
string str3 = ss.str();
//输出
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
return 0;
}
std::string str(uc, uc+sizeof(uc)/sizeof(uc[0]))
?