How to Convert unsigned char* to std::string in C++?

前端 未结 6 1362
予麋鹿
予麋鹿 2020-11-29 02:56

I have unsigned char*, want to convert it to std::string. Can you please tell me the safest way to do this?

6条回答
  •  無奈伤痛
    2020-11-29 03:42

    Here is the complete code

    #include 
    
    using namespace std;
    
    typedef unsigned char BYTE;
    
    int main() {
      //method 1;
      std::vector data = {'H','E','L','L','O','1','2','3'};
      //string constructor accepts only const char
      std::string s((const char*)&(data[0]), data.size());
      std::cout << s << std::endl;
    
      //method 2
      std::string s2(data.begin(),data.end());
      std::cout << s2 << std::endl;
    
      //method 3
      std::string s3(reinterpret_cast(&data[0]), data.size()) ;
      std::cout << s3 << std::endl;
     
      return 0;
    }
    

提交回复
热议问题