JohnnyG
Joined: 26 Jul 2009 Posts: 2
|
sprintf() and character array problem |
Posted: Sat Aug 08, 2009 11:40 pm |
|
|
I would like to use sprintf() to place values into a string, the string is formed from loading each element of the array from a serial EEPROM.
My problem is that I can recall the strings to a array of characters but when used in sprintf() the values will not fill.
The definition for sprintf is sprintf(string, cstring, values...);
cstring is a constant string or an array of characters null terminated. This I have but the result is not what I expected.
Code: | char str[32]; // Global character array - loaded from memory
char tstr[32]; // Global character array - set in sprintf
sprintf(tstr, "TIME: %2X:%2X:%2X", Hours, Minutes, Seconds); // Normal usage which works
// str is loaded with the code below to read "TIME: %2X:%2X:%2X" - it is null terminated
sprintf(tstr, str, Hours, Minutes, Seconds); // Does not work, returns nothing
|
I use the following code to retrieve string from a Microchip 24LC1025 I2C EEPROM:
Code: | i2c_start();
Ack = i2c_write(MEM_AddressWrite);
Ack = i2c_write((int)(Address >> 8)); // MSB
Ack = i2c_write((int)Address); // LSB
i2c_start();
Ack = i2c_write(MEM_AddressRead);
for (i=0; i<=Count; ++i) {
if (i < Count)
str[i] = i2c_read(); // Continuing reads
else
str[i] = i2c_read(0); // End of read
}
i2c_stop();
|
This code works, I can recall all the strings and display them, but the placeholders (%d for example) will show instead of the value that should fill it.
My test code:
Code: | printf("printf(): ");
printf(str); // str[] loaded from memory
printf("\n\r");
printf("sprintf() using str[]: ");
sprintf(tstr, Test, 5);
printf("\n\r");
printf("sprintf() using constant: ");
sprintf(tstr, "TEST UNIT #%d", 5);
printf(tstr);
|
the debug output:
Code: | printf(): TEST UNIT #%d
sprintf() using str[]:
sprintf() using constant: TEST UNIT #5
|
I am fairly new to C programming and am quite blurry on pointers, I have a feeling they might play some part in this. Anyone have any good ideas on this? |
|