Distinguish float and integer types from string

Johann Lermer johann.lermer at elvin.eu
Mon Mar 11 14:08:54 UTC 2019


On Saturday, 9 March 2019 at 18:11:09 UTC, Jacob Shtokolov wrote:
> I tried to use std.conv.to and std.conv.parse, but found that 
> they can't really do this. When I call `data.to!int`, the value 
> of "123.45" will be converted to int!

Are you sure? This here works for me:

import std.stdio;
import std.string;
import std.conv;

void main ()
{
     auto s = readln.strip;

     try
     {
         int i = to!int (s);
         writefln ("string is an int: %s", i);
     }
     catch(Exception e)
     {
         try
         {
             float f = to!float(s);
             writefln ("string is a float: %s", f);
         }
         catch(Exception e)
         {
             writefln ("string is an neither an int nor a float: 
%s", s);
         }
     }
}


More information about the Digitalmars-d-learn mailing list