BetterC, int to string?

Steven Schveighoffer schveiguy at gmail.com
Fri Jun 18 13:46:47 UTC 2021


On 6/18/21 5:05 AM, Mike Brown wrote:
> Hi all,
> 
> I would like to convert a D string to an int - im doing this in a 
> compile time function as well. conv throws an error due to it using 
> TypeInfo?
> 
> How would I do this?

std.conv.to really should support it, that seems like a bug.

But just FYI, doing string-to-int conversions is pretty easy (this 
doesn't handle overflow, but you can use core.checkedint to deal with it 
if necessary):

```d
int parseInt(string s) nothrow @safe @nogc
{
    bool isNeg = false;
    assert(s.length > 0);
    if(s[0] == '-') {isNeg = true; s = s[1 .. $];}
    int result = 0;
    foreach(c; s) {
       assert(c >= '0' && c <= '9');
       result = result * 10 + (c - '0');
    }
    return result;
}
```

-Steve


More information about the Digitalmars-d-learn mailing list