How to use sprintf

Steven Schveighoffer schveiguy at yahoo.com
Mon Apr 25 07:19:12 PDT 2011


On Sun, 24 Apr 2011 17:22:39 -0400, dsimcha <dsimcha at yahoo.com> wrote:

> On 4/24/2011 5:22 PM, Justin Hanekom wrote:
>> Hi all,
>>
>> I have what should be an *extremely* simple question that Im banging my  
>> head against: how to use
>> sprintf to format something to a string.
>>
>> I have tried:
>>    import std.stdio;
>>    ...
>>    auto buffer = new char[12];
>>    auto chars_written = sprintf(cast(char *) buffer, "%d", 12345);
>>    writeln(chars_written);
>> and various other ways of getting the buffer into sprintf, but no  
>> matter what I do the program seems to
>> die when sprintf is called.
>>
>> What I'm ultimately trying to do here is format a number with thousands  
>> separated by commas.
>>
>> Any idea?
>>
>> Thanks, Justin
>
> sprintf is a C function.  The string you passed needs to be  
> zero-terminated.  Since it's not, sprintf probably keeps trying to write  
> more stuff until it segfaults, because it never finds the zero  
> terminator.  See std.string.toStringz  
> (http://www.digitalmars.com/d/2.0/phobos/std_string.html#toStringz).

This is not true.  sprintf does not care if the destination buffer is zero  
terminated, because it actually writes the zero.  The requirement is  
simply that the buffer be large enough to handle the data.

Even the safer version of sprintf (snprintf) does not require the buffer  
to be zero-terminated before calling the function.

The problem the OP has is he is casting buffer to a char *.  He should  
just use buffer.ptr.

This should work:

auto chars_written = sprintf(buffer.ptr, "%d", 12345);

-Steve


More information about the Digitalmars-d mailing list