Attempt string-to-real conversion in D without exceptions

115 views Asked by At

Given an array of string, I want to find the first one that can be successfully converted to a real without using exceptions.

The only relevant functions I can see in Phobos are std.conv.to and std.conv.parse, but both of these will throw an exception if they cannot convert the string. I'd like to avoid exceptions because this is not going to be an exceptional circumstance for my use case.

C# provides TryParse for exactly this. Is there anything similar in D?

(of course, I could parse the string myself to determine if it is convertible to real, but it's non-trivial so I'd like to avoid that if possible).

2

There are 2 answers

5
AudioBubble On BEST ANSWER

Phobos doesn’t appear to have a way to do this without exceptions, besides std.stream. The problem is that std.stream seems to be deprecated. Here is an example using sscanf with double, though I don’t know how to do it with real:

extern (C) int sscanf(const char* input, const char* format, ...);

auto tryParseDouble(string input) {
    import std.string;
    import std.typecons;

    double result;
    if (sscanf(input.toStringz, "%lf".toStringz, &result) == 1) {
        return Nullable!double(result);
    } else {
        return Nullable!double();
    }
}

void main() {
    import std.algorithm;
    import std.range;
    import std.stdio;

    auto myArray = ["foo", "bar", "3.14", "42"];
    auto x = myArray
        .map!(tryParseDouble)
        .filter!(x => !x.isNull)
        .front
        .get;
    writeln(x);
}
0
Demi On

While sscanf() works, it is unsafe. I would open an enhancement request.

Try adapting the Phobos code, returning NaN instead of throwing.