C++ 语言中经常碰到需要将数组转成字符串,方法如下
cpp
std::string arrayToString(unsigned char* arr, int size) {
std::stringstream ss;
for (int i = 0; i < size; ++i) {
ss << arr[i];
}
return ss.str();
}
将char data[ ] 数组转换成string类型如下,通过arrayToString函数返回string 类型
cpp
int set_modelgroup(unsigned char data[],int len)
{
int r=0;
std::string ret;
std::string str;
cJSON *setjson = cJSON_Parse(k_app_setodmindex);
cJSON *message = cJSON_GetObjectItem(setjson, "message");
cJSON_DeleteItemFromObject(message, "Model_group");
str=arrayToString(data,len); // 将字符串数组转成string类型
cJSON_AddStringToObject(message, "Model_group", str.c_str());
char *modified_json = cJSON_PrintUnformatted(setjson);
std::string s2=modified_json;
if (0 == s_factoryCmd.get(modified_json, ret)) {
printf("%s\n", __func__);
printf(" - %s\n", modified_json);
printf(" - %s\n", ret.c_str());
cJSON *json = cJSON_Parse(ret.c_str());
cJSON *result = cJSON_GetObjectItem(json, "result");
cJSON *SUCCESS = cJSON_GetObjectItem(result, "SUCCESS");
if (cJSON_IsNumber(SUCCESS)) {
printf("SUCCESS: %d\n", SUCCESS->valueint);
}
cJSON_Delete(json);
return SUCCESS->valueint;
}
return r;
}