f



I want to use a printf() "template"

Like this:

char template[] = "%d    %c     %d    %.3f     %.3f     %.5f\n";
char args[]     = "i,    j,     k,   freq,     dist,    total";
printf(template, args);


As a visual aid more than anything else.


But as written it prints nonsense:

762118576    �     1845501    -nan     0.000     0.00000


when it should print

1    a     1    0.100     -0.332     0.33219



Is it possible?

0
DFS
12/20/2016 2:43:57 AM
comp.lang.c 30657 articles. 4 followers. spinoza1111 (3246) is leader. Post Follow

3 Replies
415 Views

Similar Articles

[PageSpeed] 57

On Monday, December 19, 2016 at 8:44:04 PM UTC-6, DFS wrote:
> Like this:
>=20
> char template[] =3D "%d    %c     %d    %.3f     %.3f     %.5f\n";
> char args[]     =3D "i,    j,     k,   freq,     dist,    total";
> printf(template, args);
>=20
>=20
> As a visual aid more than anything else.
>=20
>=20
> But as written it prints nonsense:
>=20
> 762118576    =EF=BF=BD     1845501    -nan     0.000     0.00000
>=20
>=20
> when it should print
>=20
> 1    a     1    0.100     -0.332     0.33219
>=20
>=20
>=20
> Is it possible?

The only way to produce multiple tokens like that is
with a macro.

char template[] =3D "%d =C2=A0 =C2=A0%c =C2=A0 =C2=A0 %d =C2=A0 =C2=A0%.3f =
=C2=A0 =C2=A0 %.3f =C2=A0 =C2=A0 %.5f\n";=20
#define args =C2=A0 =C2=A0    i, =C2=A0 =C2=A0j, =C2=A0 =C2=A0 k, =C2=A0 fr=
eq, =C2=A0 =C2=A0 dist, =C2=A0 =C2=A0total=20
printf(template, args);=20

0
luser
12/20/2016 2:55:15 AM
On Mon, 19 Dec 2016 21:43:57 -0500, DFS <nospam@dfs.com> wrote:

>Like this:
>
>char template[] = "%d    %c     %d    %.3f     %.3f     %.5f\n";
>char args[]     = "i,    j,     k,   freq,     dist,    total";
>printf(template, args);
>
>
>As a visual aid more than anything else.
>
>
>But as written it prints nonsense:
>
>762118576    ?     1845501    -nan     0.000     0.00000
>
>
>when it should print
>
>1    a     1    0.100     -0.332     0.33219
>
>
>
>Is it possible?

Considering that your format string promised printf there would be six
additional arguments and you only provided one, be thankful that the
resulting undefined behavior didn't cause any real damage.

If you change both array definitions to preprocessor directives
   #define template "%d ...."
   #define args i, j, ...
it should do what you want.

-- 
Remove del for email
0
Barry
12/20/2016 3:01:35 AM
On 12/19/2016 09:43 PM, DFS wrote:
> Like this:
>
> char template[] = "%d    %c     %d    %.3f     %.3f     %.5f\n";
> char args[]     = "i,    j,     k,   freq,     dist,    total";
> printf(template, args);
>
>
> As a visual aid more than anything else.
>
>
> But as written it prints nonsense:
>
> 762118576    �     1845501    -nan     0.000     0.00000
>
>
> when it should print
>
> 1    a     1    0.100     -0.332     0.33219
>
>
>
> Is it possible?


Thank you luser droog and Barry Schwarz.

Your answers work perfectly.


0
DFS
12/21/2016 2:28:37 PM
Reply: