printf, writeln, writefln

ryuukk_ ryuukk.dev at gmail.com
Wed Dec 7 00:35:16 UTC 2022


On Tuesday, 6 December 2022 at 23:41:09 UTC, H. S. Teoh wrote:
> On Tue, Dec 06, 2022 at 11:07:32PM +0000, johannes via 
> Digitalmars-d-learn wrote:
>> //-- the result should be f.i. "the sun is shining"
>> //-- sqlite3_column_text returns a constant char* a \0 
>> delimited c-string
>> printf("%s\n",sqlite3_column_text(res, i));
>> writeln(sqlite3_column_text(res, i));
> [...]
>
> In D, strings are not the same as char*.  You should use 
> std.conv.fromStringZ to convert the C char* to a D string.
>
>
> T


no, you don't "need" to use std conv


Here is an alternative that doesn't allocate

Make sure to read the comments


```D

// here notice where the functions are comming from
import std.stdio : writeln, writefln;

import core.stdc.stdio : printf;
import core.stdc.string : strlen;

const(char)* sqlite3_column_text(void*, int iCol)
{
     return "hello world";
}

void main()
{
     // printf is a libc function, it expects a null terminated 
string (char*)
     printf("%s\n", sqlite3_column_text(null, 0));

     // writeln is a d function, it expects a string (immutable 
slice of char aka immutable(char)[], a slice is T* + len)

     // so here we get the string from sqlite
     const(char)* ret = sqlite3_column_text(null, 0);


     // then we need to determine the length of the null 
terminated string from c
     // we can use strlen from libc

     size_t len = strlen(ret);

     // now we got a len, we can build a D string, remember, it's 
just a slice

     string str = cast(string) ret[0 .. len];

     writeln(str);
     writefln("%s", str);
}
```


More information about the Digitalmars-d-learn mailing list