Hi i am having a problem with the sprintf function. i don't know what i am doing wrong. i created a function where i use sprintf to separate the digits of a decimal number, and the first time that i called the function it works fine. The second time the sprintf starts when the first time left, and so on. The variable looks something like this the first time: "0123" and the second time: "0123123" I don't know if i have to reset a pointer (or how to do it) so everytime i call the function it starts at the beginning of the array. the code looks something like that:
void send_code (void) { int n; if (oper_code < 1000){ n = sprintf (code_char, "%d", 0); } n += sprintf (code_char+n, "%d", oper_code); . . . } void main (void) { . . . while (1) { send_code(); } }
Hi When i look at the result in the computer simulation is in the "char_code" variable in the "watch" window. As for when I burn the chip, ther is a subroutine that sends out to the serial port (uart) every element of the array such as code_char[0], code_char[1], etc. I guess the main question is "How can i tell this function "sprintf" where to start writing the result?". I have tried increasing and decreasing the size of the array but still does not work. Thanks
I can't beleive this, I replaced the zero the first time I call sprintf for a variable with them value of zero and now it works, such a stupid solution and I did not think about it before. Anyway, I don't see why it did not work, if somebody explain it would be greatly apprecciated. Here is the code:
int oper_code; char code_char[5]; void send_code (void) { int n; int p; n=0; p=0; if (oper_code < 1000){ n = sprintf (code_char, "%d", p); } n += sprintf (code_char+n, "%d", oper_code); } void main (void) { oper_code = 132; while (1) { send_code(); }
Ah, that one... You're facing an ANSI standard violation of the Keil compiler & tools: it should send your constant zero to sprintf() as an int, but it will indeed send it as a byte. To account for that, you would have to use a different sprintf() format instead of "%d". It's all in the docs to be found.
"To account for that, you would have to use a different sprintf() format instead of "%d"." Or, if you prefer to retain portability, cast the parameter to int. My preference, however, would be to go with the original suggestion and use the Keil specific "%bd" instead.
or direct:
if (oper_code < 1000){ code_char[0]='0'; code_char[1]=0x00; n = 1; }
Thank you all. You've helped a lot.
If your objective is just to left pad the value with zeroes in a field width of four you can get rid of n, p and the if test and use this instead: sprintf (code_char, "%04d", oper_code);