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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

formatting a char*

Status
Not open for further replies.

bitwise

Programmer
Mar 15, 2001
269
US
I need to do one sprintf statement to format a char array, but it has one weirdness. Example:

int padding;
char format[n];
...

padding=10;
sprintf(format,"%%-%ds%.3f\n", padding, 3.141592654);
printf(format, "some text");

OUTPUT:
some text 3.142

Ok, here's the problem. What if I what to add the "some text" string into the format character array during the sprintf call, and not during the printf call? I have tried an arrangment of things, but can't see to find the one formatting string that does it all. Ideas?

Thanks,
-bitwise

I initially thought this would work:
sprintf(format,"%-%ds%.3f\n", padding, "some text", 3.141592654);

This does not work, and for obvious reasons. Any other ideas?
 
You may be approaching this from the wrong end. Try building your format string (just consisting of conversion specifiers) and then passing printf() the format string and the values that corresponding to the specifiers:

int padding=10;
char format[100];

sprintf(format,"%%-%ds%%.3f\n",padding);

/* now format contains "%-10s%.3f\n" */

printf(format,"some text",3.141592654);

Russ
bobbitts@hotmail.com
 
I understand that, and that would be the best way to do it if you simply wanted to print out the char array. I was using printf only for demonstration purposes. I really need to get the value into one string (namely 'format' char array). I'm not printing the string out to the console. It is going to be used for something else, and it needs to be in that format. Printing it out with printf is only a means for testing if it was built correctly with sprintf. So is it possible to get it in the correct format all in one sprintf call?

Thanks Again,
-bitwise
 
In one call, no, because you have to create the format string that contains your "dynamic padding" first -- sprintf() can't use the padding in the 1st call because you haven't created it yet.

But, can you settle for two sprintf()s?

int padding=10;
char format[100];
char result[100];

sprintf(format,"%%-%ds%%.3f",padding);
sprintf(result,format,"some text",3.141592654);

HTH,

Russ
bobbitts@hotmail.com
 
I was close to that earlier but just missed it. Like always, thanks!

-bitwise
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top