Thanks.. I'm using C18 for PIC18F4550..
Actually, its for LCD.. I'm trying to do a stopwatch using PIC..
Code:
sprintf (buffer," %d:%d:%d:%d ", hr, min, s, ms);
Lcd_Write_String(1,buffer);
That is to print the value onto the LCD but the text is not formatted correctly because some values are 1 digit and some are 2 digits etc..
can the code u showed me use in this scenario..?
Yes. It would look something like this:
Code:
sprintf (buffer," %02d:%02d:%02d:%03d ", hr, min, s, ms);
Lcd_Write_String(1,buffer);
The first '0' (zero) after the '%' indicates that the value should be zero-padded. The number following that '0' says what the full width of the printed number should be. Above I've chosen widths of 2 (i.e. '01, '02', '22', etc.) except for milliseconds, where you need a width of 3.
There are many other options and rules for using sprintf formats. I strongly suggest that you Google 'sprintf' and read the first link. Also, the output format specifiers are fully documented in the
C18 library manual, section 4.7.2, under 'fprintf()' (which is another function which uses the same formatting).
The beginning of section 4.7 contains some other information about this family of functions which may be of interest to you. For instance, floating-point specifiers are not supported. This probably won't be important in your current project but might be in the future.
comparing printf to sprintf, is print better..?
They use the same code internally, so the answer to that depends entirely upon the situation. If you want to print directly to where-ever the standard output is going, then printf() is probably easier. If you just want to easily format a string for use within the program or for printing to another output, then you are pretty much going to have to use sprintf() like you have in your example.
Of course, C18 might have facilities for redirecting printf()'s output to your LCD--I have never used PICs so I don't know. I have reason to believe I may be using them shortly, however.
Torben