Convert from console input

Gide Nwawudu gide at btinternet.com
Fri Apr 10 06:48:17 PDT 2009


On Fri, 10 Apr 2009 05:55:57 -0400, Sam Hu <samhudotsamhu at gmail.com>
wrote:

>Hello everybody ,
>
>I'am learning D2.028+Phobos and wrote a excise which purpose is to write a generic method which an retrieve the console input with desired type.Say if I want the user to input an integer to the console,or a double to the console,just write below code:double salary=askfor!(double);
>Below is my attemp :
>
>askForInput.d
>module askForInput;
>
>import std.stdio;
>import std.conv;
>import std.c.stdlib;
>
>T askfor(T)()
>{
>    char[]msg=cast(char[])"Please enter ";
>    char[] temp;
>    static if(is(T==int) || is(T== long ))
>        temp=cast(char[])"an integer";
>     else static if(is(typof(T[])==char[])|| is(typeof(T[])==dchar[]) || is(typeof(T[])==wchar[]))
>        temp=cast(char[])"a string";
>     else static if(is(typeof(T)== short)|| is(typeof(T)==float)|| is(typeof(T)==double))
>        temp=cast(char[])"a decimal";
>     char[] retval=msg~temp~" :";
>     writef(retval);
>    
>
>     //try
>     //{
>        char[] input=cast(char[])readln;
>        return to!(T)(input);
>     //}
>     //catch(ConvError whatever)
>     //{
>     //   writefln("Cannot convert.Error occurred.");
>        
>     //   return T.init;
>     //}
>    
>}
>int main(char[][] args)
>{
>    int test=askfor!(int);
>    writefln("you entered %d",test);
>
>    getchar;
>
>    return 0;
>    
>}
>
>It compiled but threw an ConvError when running:
>
>D:\Laguage\Dex>dmd askforinput.d
>
>D:\Laguage\Dex>askforinput
>Please enter an integer :4
>std.conv.ConvError: conversion Can't convert value `
>' of type const(char)[] to type int
>
>D:\Laguage\Dex>
>
>I have no clue why the convertion is not permitted.Could anybody here help me?Thanks so much!
>
>Regards,
>Sam

There is a trailing newline in the input, use the chomp function to
remove it.

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

void main() {
    char[] input=cast(char[])readln;
    writefln("'%s'",input);
    input = chomp(input);
    writefln("'%d'",to!(int)(input));
}

[OT] Should chomp be defined as 
void chomp(C)(ref C[] s, in C[] delimiter = null);
- instead of -
C[] chomp(C)(C[] s, in C[] delimiter = null);

?

Gide


More information about the Digitalmars-d-learn mailing list