daisy
daisy

Reputation: 23541

snprintf with "%0*d" , too few arguments

I needed to dynamically generate a string like the following:

001 / 192

However , the number of digits varies , thus i must define another variable , called print_width , which is , in this case: 192 % 10

snprintf ( statusString , 30 , "%0*d / %0*d" , snprintf_width , completed[tid] , total[tid]);

The code above posed a compiler warning: too few arguments , and not working

Upvotes: 2

Views: 1870

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754450

You need an integer width argument for each * as well as for each d in the format. You've provided 3 of the requisite 4 arguments, and your compiler is kind enough to tell you, rather than producing garbage at run time.

Hence, for example:

if (snprintf(statusString, sizeof(statusString), "%0*d / %0*d", snprintf_width,
             completed[tid], snprintf_width, total[tid]) >= sizeof(statusString))
    throw "Oops - string was too small for data";

Upvotes: 5

pm100
pm100

Reputation: 50190

you need the width twice (you have * twice)

Upvotes: 1

Related Questions