View previous topic :: View next topic |
Author |
Message |
pmuldoon
Joined: 26 Sep 2003 Posts: 218 Location: Northern Indiana
|
sprintf %s not working as expected |
Posted: Mon Sep 24, 2018 7:47 am |
|
|
compliler v5.074
PIC 18F66K22
I seem to be having trouble with the %s format specifier. I am trying to fix the string length so not to overflow my tiny LCD display line memory of 20 characters. Using %5s should pad the string, %5.5s should truncate or pad as necessary to get 5 chars. Neither seem to work as expected. In all cases the entire length of the string is inserted as if it were just %s.
I've reduced the problem down to a simple snippet I've inserted into main() and have been testing with the PICSIM tool.
Code: |
void main()
{
// testing %#s bug
#define TESTREV "1.23"
char TestStr[25];
sprintf(TestStr,"TestStr %5.5s ",TESTREV);
while(1);
|
Is there something I'm missing, or not doing right. Or is it a limitation of the compiler? |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19549
|
|
Posted: Mon Sep 24, 2018 9:57 am |
|
|
It is a compiler limitation. Like -, which doesn't work either.
You just have to truncate the string before printing. Either just add a null terminator at character 6, or use strncpy to copy it into another array. |
|
|
pmuldoon
Joined: 26 Sep 2003 Posts: 218 Location: Northern Indiana
|
|
Posted: Mon Sep 24, 2018 10:10 am |
|
|
Understandable.
I can work around it.
Thanks, |
|
|
pmuldoon
Joined: 26 Sep 2003 Posts: 218 Location: Northern Indiana
|
|
Posted: Mon Sep 24, 2018 11:46 am |
|
|
I guess it would have been nice if the compiler could at least throw an error if there is anything between the '%' and 'S' since it doesn't support a standard feature. Even just a syntax error would have been helpful. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19549
|
|
Posted: Mon Sep 24, 2018 12:38 pm |
|
|
Yes.
In fact given how close to fully working the compiler is now, these are both 'lacks' that CCS might like to consider correcting. Worth pointing this out to them. |
|
|
jeremiah
Joined: 20 Jul 2010 Posts: 1357
|
|
Posted: Fri Sep 28, 2018 12:18 pm |
|
|
I made a hack of an snprintf function if you want a general solution.
https://www.ccsinfo.com/forum/viewtopic.php?t=53652&highlight=snprintf
Note that it currently returns the number of characters it would have written had max not held it back (for debugging purposes). I did this since you can always call strlen on the result to see the actual number of chars written.
It should always append a null, so if you specify a max of 5, it will do 4 characters and a null character. |
|
|
|