some problem with strcat

Hi,

I have some problem with strcat, and I have no idea where the problem is.
I have following code for example.

some declaration

char dep1[6] = "00:00";
char dep2[6] = "00:00";
char divTime[3] = "00";

for my better understanding:
dep1 is an array = |0|0|:|0|0|\0|
dep2 is an array = |0|0|:|0|0|\0|
divTime is an array = |0|0|\0|
I hope so far thats correct.

the I have a function like this:

void getDepartures() {
  int i = 0;
  char jsonResponse[20];
  char *ptr;
  Process p;

  p.runShellCommand("/mnt/sda1/arduino/www/timetable/curl.php -t");
  while (p.running());
  while (p.available()) {
    char c = p.read();
    jsonResponse[i] = c;
    i++;
  }

Serial.println(jsonResponse);


  ptr = strtok(jsonResponse, ","); // get first time
  strncpy(dep1, ptr, 6);
  
Serial.println(dep1);

  ptr = strtok(NULL, ",");         // get second time
  strncpy(dep2, ptr, 6);

Serial.println(dep2);

  ptr = strtok(NULL, ",");         // get div time
  strncpy(divTime, ptr, 3);

Serial.println(divTime);

  strcat(divTime, "'");
Serial.println(divTime);
}

The response:
jsonResponse is an array = |1|2|:|3|8|,|1|3|:|4|5|,|2|6|\0| | | | | |

What I get on the serial monitor
22:38,23:08,26�
22:38
23:08
26�23:08
26�23:08'

What I not understand is this last part ..
26�23:08
26�23:08'

  ptr = strtok(NULL, ",");         // get div time
  strncpy(divTime, ptr, 3);

Serial.println(divTime);

  strcat(divTime, "'");
Serial.println(divTime);

I would expect that the last two values are
26
26'

somewhere I was going a mistake ....

Thanks for helping.

Either set the jsonResponse array to all zeros, or this:

  while (p.available()) {
    char c = p.read();
    jsonResponse[i] = c;
    i++;
// add this
    jsonResponse[i] = 0;
  }

divTime is a three element array.
How can it contain, as a C string, "26'"?

AWOL:
divTime is a three element array.
How can it contain, as a C string, "26'"?

like this
| 2 | 6 | \0 |
or I'm wrong :roll_eyes:

2 6 '. \0

I make that four characters, including terminator.

strncpy() does not produce a nul terminated string if you get to the “n”.

So if you try to copy “12:38” using strncpy(X,Y,3) you get ‘1’ ‘2’ ‘:’ but no ‘\0’

SurferTim:
Either set the jsonResponse array to all zeros, or this:

  while (p.available()) {

char c = p.read();
   jsonResponse[i] = c;
   i++;
// add this
   jsonResponse[i] = 0;
 }




ok, looks better. I got now

22:38,23:08,02
22:38
23:08
02'

so far so good ...

@KeithRB

so I have to add "\0" at the end of each

ptr = strtok(jsonResponse, ",");
strncpy(dep1, ptr, 5);
dep1[6]= "\0";

ptr = strtok(NULL, ",");
strncpy(dep2, ptr, 5);
dep2[6]= "\0";

or just

// -> 22:38,23:08,02

// -> 22:38
ptr = strtok(jsonResponse, ",");
strcpy(dep1, ptr);
dep1[6]= "\0";

// -> 23:08
ptr = strtok(NULL, ",");
strcpy(dep2, ptr);
dep2[6]= "\0";

AWOL:
2 6 '. \0

I make that four characters, including terminator.

Right :smiley:

THANKS 4 help. It’s working proper now!!