Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String formatting

Status
Not open for further replies.

kartoffel

Programmer
Jul 24, 2002
15
CA

How can I specify formatting options (ex: setw(4)) to a string using the sprintf function.

Example:
=============
char currentPosition[250];
sprintf(currentPosition, "X position: %f Y position: %f Z position %f", xPos, yPos, zPos)
=============
I want xPos, yPos and zPos to always be 4 characters wide.
What is the way to do this?

Also, if I use "char* currentPosition" to declare my string, I get an application error. Why is that?

Thanks
 
sprintf(dest, "%4d", ival); // integer will be printed and occupy (at least) 4 positions (if ival is 12345, it will occupy 5 positions).

sprintf(dest, "%04d", ival); // integer will be printed and occupy (at least) 4 positions, but leading 0's will be used if the output is shorter than 4.

OBS OBS :
%d means you will supply integer argument to sprintf, not floating points, or strings or .....

There are lots of possibilites - you need to check documentation :
"Format Specification Fields: printf and wprintf Functions"

<Also, if I use &quot;char* currentPosition&quot; to declare my string, I get an application error. Why is that?
>
You can't just put in a pointer ... it needs to point to some memory owned by your application.
Allocate a buffer and let the pointer point to this buffer :

char buf[256];
char * CurrentPosition = buf;
sprintf(CurrentPosition, &quot;..................&quot;, ....);

/JOlesen
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top