Setting width of INT variable C18 Compiler

Thread Starter

lostinspace73

Joined Jan 21, 2011
6
I need to display variable 'a' with values ranging from 0 - 9999 and another variable 'b' on the same line of the display.

The trouble I'm having is when the value of 'a' goes from 4 digits to 3, 2 or 1 digit the output associated with variable 'b' shifts to the left leaving a 'shadow' of the previous output on the screen.


the statement,

fprintf(_H_USER, "\nP: %dW Acc: %dWh", P,Acc);

displays,

P: 1234W Acc: 12Wh

then,

P: 987W Acc: 14Whh

and,

P: 65W Acc: 15WhWh

If anyone reading this knows how to set the width of INT P to four digits, I would be very grateful for some direction.

Thanks
 

John P

Joined Oct 14, 2008
2,026
I respectfully disagree with Mr Spook. What's wanted here is a format for printing that makes a number come out the same length every time.
Rich (BB code):
Instead of 
fprintf(_H_USER, "\nP: %dW Acc: %dWh", P,Acc);

try 
fprintf(_H_USER, "\nP: %4dW Acc: %2dWh", P,Acc);

this should say
P:   65W Acc: 15Wh  (number is padded with spaces to make 4 characters)

or if you use 
fprintf(_H_USER, "\nP: %04dW Acc: %02dWh", P,Acc);

you should get
P: 0065W Acc: 15Wh  (number is padded with zeroes instead)
Code tags used because multiple spaces were being swallowed by computer.
 

ErnieM

Joined Apr 24, 2011
8,377
Library routines such as fprintf() are VERY HEAVY DUTY and need a lot of program space to live, and as you see can be more of a pain then a helpful code source. I don't think there is a way to specify how many characters a int should use as there is for floats.

The simplest way to fix this is to use the return value of fprintf(). That contains HOW many characters it used, and assuming you have a 20 character display just print the next (20-fprintf()) characters as a space.

When I am coding for displays I tend to make strings inside buffers so I can fine tune things better.

Assuming a 20 character display (so I can number the character spots):

Your program (when printing trailing blanks):
Rich (BB code):
01234567890123456789
P: 1234W Acc: 12Wh
P: 987W Acc: 14Wh
P: 65W Acc: 15Wh
Now when I do things like this I prefer my number to stay in the same place:

Rich (BB code):
01234567890123456789
P: 1234W Acc: 123Wh
P: 123W  Acc: 12Wh
P: 12W   Acc: 1Wh
Or even:

Rich (BB code):
01234567890123456789
P: 1234W  Acc: 123Wh
P:  123W  Acc:  12Wh
P:   12W  Acc:   1Wh
That can be done using the itoa() (int to ASCII) function inside the C18 library and a little string manipulation.
 

Thread Starter

lostinspace73

Joined Jan 21, 2011
6
Thanks a million folks...I will likely try John P's version first as it looks to be quite straight forward. But don't worry, ErnieM...I'll look into your solution too for future reference. Thanks again.
 
Top