Convert from console input
Sam Hu
samhudotsamhu at gmail.com
Fri Apr 10 02:55:57 PDT 2009
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
More information about the Digitalmars-d-learn
mailing list