asking
March 8, 2023, 11:18am
1
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 ?
J-M-L
March 8, 2023, 11:34am
3
"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
Koepel
March 8, 2023, 11:34am
4
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
J-M-L
March 8, 2023, 11:40am
5
you should use snprintf()
to not overflow
Of course, snprintf() is only as good as the parameters that you pass it
J-M-L
March 8, 2023, 11:53am
8
yes, that too. Your answer in post#2 is still to the point. OP should not post snippets (Snippets R Us! )
asking
March 8, 2023, 12:03pm
9
sorry for mis-out. i have edited my post for incomplete information.
Koepel
March 8, 2023, 12:15pm
10
I hope you are not using 6 bytes for the buffer now
gcjr
March 8, 2023, 12:27pm
11
asking:
char result[5];
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
system
Closed
September 4, 2023, 12:27pm
12
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.