d programming, parse or convert string to double

自闭症网瘾萝莉.ら 提交于 2019-12-08 15:59:32

问题


as easy as it is in other languages, i can't seem to find an option in the d programming language where i can convert a string (ex: "234.32") into a double/float/real.

using atof from the std.c.stdio library only works when i use a constant string. (ex: atof("234.32") works but atof(tokens[i]); where tokens is an dynamic array with strings doesn't work).

how to convert or parse a string into a real/double/float in the d-programming language?


回答1:


Easy.

import std.conv;
import std.stdio;    

void main() {
    float x = to!float("234.32");
    double y = to!double("234.32");

    writefln("And the float is: %f\nHey, we also got a double: %f", x, y);
}

std.conv is the swiss army knife of conversion in D. It's really impressive!




回答2:


To convert from most any type to most any other type, use std.conv.to. e.g.

auto d = to!double("234.32");

or

auto str = to!string(234.32);

On the other hand, if you're looking to parse several whitespace-separated values from a string (removing the values from the string as you go), then use std.conv.parse. e.g.

auto str = "123 456.7 false";

auto i = parse!int(str);
str = str.stripLeft();
auto d = parse!double(str);
str = str.stripLeft();
auto b = parse!bool(str);

assert(i == 123);
assert(d == 456.7);
assert(b == false);


来源:https://stackoverflow.com/questions/12605641/d-programming-parse-or-convert-string-to-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!