<分区>
这是我的名为 trim 的函数,它去除了它的引号字符串:
const char* trim(const char* c) {
const char *pos = c;
//Getting the length of the string
int c_length = 0;
while (*pos != '\0') {
c_length++;
pos++;
}
cout<<"\nThis is the length of string:"<<c_length;
char c_store[c_length-2]; // Removing two for the quotes
pos = c;
const char* quote = "\"";
char ch;
int i;
for (i = 0; *pos != '\0'; pos++){
ch = (char)*pos;
if(ch!=*quote) {
c_store[i] = (char)*pos;
i++;
}
}
c_store[i]='\0'; // Adding the null terminating character
const char * c_trimmed = c_store;
cout<<c_trimmed; // Prints the string CORRECTLY here !!
return c_trimmed; // There is problem when it returns, see main
}
现在我正在读取 json::value 对象,使用 toStyledString() 将值转换为字符串,然后使用 c_str() 将其转换为 const char*。我发现这个字符串周围有引号,所以我将这个值传递给函数 trim。当值返回时,返回的字符串最后被两个字符截断。这是我认为问题所在的主要地方:
int main(int argc, char** argv) {
// Reading json config file into a Json::Value type
char* config_file = read_file_into_string(argv[1]);
Json::Value Bootloading_config = create_json_object(config_file);
const char* bucket_name_json = Bootloading_config["Bootloading"]["bucket_name"].toStyledString().c_str(); // Storing value from json
const char* bucket_name_trimmed = trim(bucket_name_json); // Using trim function
const char* bucket_name = "nikhil-hax"; // Assigning another pointer for comparison
printf("\n Trimmed bucket_name:%s", bucket_name_trimmed); // It is printing the string with the last two chars cut out
if(strcmp(bucket_name_trimmed,bucket_name) == 0) // To check
cout<<"\nTRIM function Worked!!";
else cout<<"\nNOT working, look closer";
}
是否存在某处内存泄漏或我忽略的其他一些细节?一些帮助将不胜感激。谢谢