Looking for a better way to write numbers to strings

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I've been using sprinft in my code to convert strings and numbers into strings.

xxxstr is an char array of 19 characters
Numbers are all 32bit unsigned int.

		sprintf(Speedstr,   "Speed     #4.4u km/h ",Speed);
		sprintf(Diststr,    "Dist      #4.4u km   ",Distance);
		sprintf(PowerInstr, "Power in  #4.4u kW   ",Powerin);
		sprintf(PowerOutstr,"Power Out #4.4u kW   ",Powerout);

Then I'm displaying them on a 20x 4 LCD.

However when I try and send the contents of Speedstr over usart, the Speedstr file is coming out with the Distance and Powerin in the same file. Strangely enough, not Powerout. Is there a better way to write/buffer integers to strings so that they don't all end up in the same file?

I have 4 menus and this is going to cause havoc otherwise.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

ZAPrime wrote:
xxxstr is an char array of 19 characters
Numbers are all 32bit unsigned int.
For starters, your buffers are too small. The first format string you gave will generate a minimum of 21 characters plus the null termination (the others probably overflow, too - I didn't check).

The itoa() and ltoa() functions have a smaller footprint than sprintf() but you'll have to do the padding/alignment yourself; something that isn't particularly difficult.

Don Kinzer
ZBasic Microcontrollers
http://www.zbasic.net

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

yes, watch the string lengths, you will find that if you declare them too short, they will write over each other.

char Speedstr[19];
char Diststr[19];

"Speed     #4.4u km/h ",

== 20 char + null
change to

char Speedstr[21];
char Diststr[21];

give youself some room, unless you are really short of ram.

the string is 20 long + the null end of string
always remember to work out the string length +1

_________________________________

www.proficnc.com
_________________________________
Go Aussie Go!!!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:
Numbers are all 32bit unsigned int.

Then you need "#4.4ul" in sprintf().

/Martin.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Since you appear to expect 4 digit integers, there is little point in using uint32_t types.

I forget what happens with the integer precision modifier. Does it produce **** if you are too wide, or write the full width?

You definitely need larger string buffers. And use the appropriate format string for the argument type.

David.