D: Convert/parse uint integer to string. (@nogc)

kdevel kdevel at vogtner.de
Thu Nov 30 22:10:30 UTC 2023


On Friday, 24 November 2023 at 13:05:30 UTC, Ferhat Kurtulmuş 
wrote:
> [...]
> ```
> import core.stdc.stdio : sprintf;
> import core.stdc.math : log10;
>
> import std.exception : assumeUnique;
> import std.stdio : writeln;
>
>     size_t nod(int num){
>       return cast(size_t)((num==0)?1:log10(num)+1);
>     }
>
>     void main()
>     {
>        int myint = 23;
>
>        char[80] str;
>
>        sprintf(str.ptr, "%d", myint);
>
>        string _dstring = str[0..nod(myint)].assumeUnique;
>
>        writeln(_dstring);
>
> }
> ```

What happend to the indentation? Anyway

```
$ ./inttostr -1

$ ./inttostr -2147483648

```

I like `snprintf`:

```d
import core.stdc.stdio : snprintf;
import std.exception : assumeUnique, enforce;
import std.stdio;
import std.conv;
import core.stdc.locale;
import std.format;

void main (string [] args)
{
    setlocale (LC_NUMERIC, "");
    auto myint = args[1].to!long;
    char[27] str;
    auto n = snprintf(str.ptr, str.sizeof, "%'ld", myint);
    enforce (n < str.sizeof, "buffer too small");
    string _dstring = str[0..n].assumeUnique;
    writeln(_dstring);
}
```

```
$ ./l2s -9223372036854775808
-9.223.372.036.854.775.808
```



More information about the Digitalmars-d-learn mailing list