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!

interpolating a value into a formatting string

Status
Not open for further replies.

bitwise

Programmer
Mar 15, 2001
269
US
I'm trying to generate some dynamic string padding so things line up correctly, well my question is, how can I get a variable value into a printf string statement so that it is not hardcoded in. For example,

int val=10;
printf("%-5s:%s", str1, str2);

That would right-align things padding the strings by 5 via the difference from the length of str1 and 5.

he :str2
hello:str2
see :str2

Well, what if I wanted to use 'val' instead of 5. How can I have printf use the value of 'val' instead? Is this possible?

Thanks,
-bitwise
 
Use sprintf instead of printf

for Example:

char formatstr[nn];

sprintf(formatstr,"format",arguments);
printf(formatstr, parm1,parm2.....);

hnd
hasso55@yahoo.com

 
That is not going to work. I still run into the same problem, namely not being able to put the value of 'val' into the string correctly. For example,

char formatstr[nn];

sprintf(formatstr, "%-%ds:%s\n", val, str1, str2);
printf(formatstr);

That does not work. val does not get placed into the formatting string, it gets confused. This works:

sprintf(formatstr, "%-5s:%s\n", str1, str2);
printf(formatstr);

But that is not what I want. I want to change the value of 5 to something I compute at runtime to achieve dynamic padding. I just want to replace 5 with a variable name, but I can't seem to find a way to do it.

Thanks,
bitwise
 
You have to precede % characters with another '%' to unconfuse sprintf(). Try something like this:

char formatstr[N];
char str1[]="foo";
char str2[]="bar";
int val=10;

sprintf(formatstr,"%%-%dd%s:%s\n",val,str1,str2);
printf(formatstr,40);

Russ
bobbitts@hotmail.com
 
Thanks, guys! I've got it working now, and have learned yet another trick thanks to the programming talents on this forum - man I'm glad I found this place.

Thanks,
-bitwise
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top