0

In the code below, when "data" is printed with:

Display_printf(display, 0, 0, "score received: %.*s\n", ret, data);

the json data is printed correctly:

{"zip":97306,"score":130}

However, when I do this:

Display_printf(display, 0, 0, "score received: %s\n", data);

the json data contains extra characters (sometimes weird/unknown chars) like this:

{"zip":97306,"score":130}R

Why does the second print method show extra characters wheras the first one doesn't? How can I fix it so that the second print method works? What is the equivalent code for doing "%.*s", so that data can store the correct json data?


do
{
    ret = HTTPClient_readResponseBody(httpClientHandle, data, sizeof(data),
                                      &moreDataFlag);
    if(ret < 0)
    {
        printError("httpTask: response body processing failed", ret);
    }
    Display_printf(display, 0, 0, "%.*s \r\n",ret,data);
    len += ret;
}
while(moreDataFlag);
Alex Feng
  • 45
  • 1
  • 9
  • Possible duplicate of [What does "%.\*s" mean in printf?](https://stackoverflow.com/questions/7899119/what-does-s-mean-in-printf) – Mathieu May 23 '19 at 07:28
  • @Eric Postpischil I accidentally forgot to put that in the post. I've updated the post now. – Alex Feng May 23 '19 at 16:02

2 Answers2

3

My guess is that the data you receive by HTTPClient_readResponseBody isn't a null-terminated byte string.

When you use

Display_printf(display, 0, 0, "%.*s \r\n",ret,data);

you specify the length of the string with the ret argument, so the printf formatting will not print anything after the specified length.

When you use plain "%s" the printf formatting will attempt to find the end of the string by finding the terminating null character '\0'.

Either keep your current method with "%.*s" and passing the length; Or pass sizeof(data) - 1 as the max length to receive, and explicitly add the null-terminator at the correct position (data[ret]).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Going of what @Some programmer dude said, I used another char array to substring "data" of size "len". This achieves what I wanted, and now it doesn't contain any extra characters.

// Substring from 0 to len of data (removes extra characters)
char json[len+1];
int c = 0;
for(; c<len; c++) {
    json[c] = data[c];
}
json[c] = '\0';

Display_printf(display, 0, 0, "json received: %s\n", json);
Alex Feng
  • 45
  • 1
  • 9