chipKIT® Development Platform

Inspired by Arduino™

sprintf question

Created Thu, 01 Mar 2012 05:44:54 +0000 by KP_OZ


KP_OZ

Thu, 01 Mar 2012 05:44:54 +0000

I have a Chipkit Uno using the MPide 1.0 A simple C function - sprintf - seems to return incorrect results. Could some one kindly point our my error. Here is the code :

char buff[50]; // a buffer for sprintf to use int num=17; // an integer void setup(){ Serial.begin(9600); }

void loop() {
sprintf(buff,"%4.2d ", num); // format parameter - width of 4 and precision for the integer of 2. Serial.println(buff); }

I had expected the result of - {space} {space} 17 - eg width 4 with 2 numerics. The actual result is 17. eg no spaces. It appeared to ignore the width parameter.

If you change the format string to "%6.2d" it will print {space} {Space} 17. eg width of 4, not 6. Likewise, "%8.2d" will result in - {4 spaces} 17. Width of 6, not 8.

A format string of "%8.4" results in 0017 - no spaces. A format string of "%10.4" results in {space} {space} 0017.

Appreciate any assistance ................regards................Keith .