javick82
Joined: 12 Jul 2007 Posts: 43
|
sprintf() messing with stored values |
Posted: Fri Aug 03, 2007 11:57 am |
|
|
I have been messing with a code to test a concept I have for a project I am working on. I want a function that performs a command based on a string input. (see print_numbers() for a crude example).
The problem I am facing is when I use sprintf(str,"%c%c%c",getc(),getc(),getc()) the variable "value" gets messed up. But, when "value" is written to "holder", sprintf() is performed, and "holder" is written back to "value", the function works properly. I would like to use sprintf() to define the function parameter obviously w/o the dummy variable so the code is more readable (applies to application, not this test file).
Compiler >v4.0
Code: | #include <16f877a.h>
#fuses HS,NOLVP,NOWDT,PUT
#use delay(clock = 20000000)
#use RS232(baud = 9600, xmit = PIN_C6, rcv = PIN_C7)
void print_numbers(int number, char *output)
{
printf("Data:\n\r%c%c%c\n\r%u\n\r",output[0],output[1],output[2],number);
if(output[0] == 'h' && output[1] == 'e' && output[2] == 'x')
printf("Value in hex: 0x%x\n\r", number);
else
{
if(output[0] == 'b' && output[1] == 'i' && output[2] == 'n')
printf("Can't print binary numbers\n\r");
else
{
if(output[0] == 'd' && output[1] == 'e' && output[2] == 'c')
printf("Value in dec: %u\n\r", number);
else
printf("OOPS!");
}
}
}
void main()
{
char command[3];
int value;
int holder;
while(1)
{
printf("\n\rEnter value (000-255):\n\r");
value = 100*(getc()-48);
printf("\n\r%u\n\r",value);
value = value+(10*(getc()-48));
printf("\n\r%u\n\r",value);
value = value+(getc()-48);
printf("\n\r%u\n\r",value);
//holder = value;
printf("\n\rEnter output format (hex/bin/dec):\n\r");
sprintf(command, "%c%c%c", getc(),getc(),getc());
//value = holder;
printf("\n\r%u\n\r",value);
print_numbers(value, command);
}
} |
Thanks! |
|