這個隱含兩個細節:
uc沒有"\0"結尾,因此冒然當字串賦值給string或CString,在正常字串後面要出亂碼(不知道如何結尾)
這是unsigned 字元陣列,和一般的char array =>string不同,需要強制型別轉換。
方法很多,如下列舉3種:【我用的GCC編譯器, 用string演示;VC的CString方法相同】
#include <iostream>#include <string>#include <algorithm>#include <iterator>#include <sstream>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<const char*>(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<char>(ss)); string str3 = ss.str(); //輸出 cout << str1 << endl; cout << str2 << endl; cout << str3 << endl; return 0;}
這個隱含兩個細節:
uc沒有"\0"結尾,因此冒然當字串賦值給string或CString,在正常字串後面要出亂碼(不知道如何結尾)
這是unsigned 字元陣列,和一般的char array =>string不同,需要強制型別轉換。
方法很多,如下列舉3種:【我用的GCC編譯器, 用string演示;VC的CString方法相同】
#include <iostream>#include <string>#include <algorithm>#include <iterator>#include <sstream>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<const char*>(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<char>(ss)); string str3 = ss.str(); //輸出 cout << str1 << endl; cout << str2 << endl; cout << str3 << endl; return 0;}