Concatenate using Sprintf %d%c (3 digit number + 1 Character)

Hi,

I am trying to convert 110 + A (%d,%c) using sprinf but results are weird in serial monitor. (getting 10734���?���) instead of 110A.

using ESP32 Dev Kit V1 Hardware

int k = 0;
int digit3 = 110;
char alphabet[3] = {'A','B','C'};
char result[5];
sprintf(result, "%d,%c", digit3, alphabet[k]); // generate cstring "110A"
Serial.println(result);

what could be wrong in above code ?

Please post a small but complete sketch that shows the problem. How are digit3 and k declared, for instance ?

"110,A" that's 5 bytes for the text and one extra byte for the trailing nul char. so your result array is too small.

2 Likes

Set the baudrate of the Serial Monitor to the same baudrate as in your sketch.

The buffer for the result is too small. A "%d" can be 6 characters for a 16 bit integer or 11 for a 32 bit integer, plus 1 for the comma, plus 1 for "%c", plus a zero-terminator. So 14 is the absolute minimum. I could have calculated it wrong, so can you make it 20 ?

char result[20]; 
1 Like

you should use snprintf() to not overflow

Noted. Thanks

Of course, snprintf() is only as good as the parameters that you pass it

yes, that too. Your answer in post#2 is still to the point. OP should not post snippets (Snippets R Us!)

sorry for mis-out. i have edited my post for incomplete information.

I hope you are not using 6 bytes for the buffer now :scream:

unless you're very tight on memory, just define a char array with more than enough length (e.g. 80) as a global for use in these situations

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.