I don't get the exception on Linux after a new line, I have to wait
until EOF, which is typically the end of the program if reading from
STDIN. Not very useful.
import std.stdio;
T readNumber(T)()
{
T result;
stdin.readf("%s", &result);
return result;
}
void main()
{
try
{
int n = readNumber!int();
writeln(n);
float f = readNumber!float();;
writeln(f);
}
catch(Exception e)
{
writeln(e.msg);
}
}
Sample execution:
-----------------------
[kai.meyer@kai-rhel6 D]$ dmd -run readnum.d
a
1
1.2
** I hit Ctrl-D here, so this line isn't part of the output ***
std.conv(1157): Can't convert value `a
1
1.2
' of type LockingTextReader to type int
-----------------------
Or if you prefer with out my terminal echoing my input:
-----------------------
[kai.meyer@kai-rhel6 D]$ echo -e 'a\n1\n1.2\n' | dmd -run readnum.d
std.conv(1157): Can't convert value `a
1
1.2
' of type LockingTextReader to type int
----------------------
On 11/10/2011 02:58 PM, Tobias Brandt wrote:
import std.stdio;
T readNumber(T)()
{
T result;
stdin.readf("%s",&result);
return result;
}
Throws a ConvException if the input string wasn't in the right format.
On 10 November 2011 22:48, Fabian<talk2...@online.de> wrote:
Hey guys.
I just want to write a few console applications. Usualy I have to read numbers
to calculate some values. But what's the smartest way to read and convert the
input?
I've coded these lines:
import std.stdio, std.string, std.conv;
T readNumber(T)()
{
string buffer;
stdin.readln(buffer);
buffer = chomp(buffer);
if(isNumeric(buffer))
{
return parse!T(buffer);
}
else
{
throw new Exception("Input is not a number!");
}
}
void main()
{
try
{
int n = readNumber!int();
writeln(n);
float f = readNumber!float();
writeln(f);
}
catch(Exception e)
{
writeln(e.msg);
}
}
Can I use that function or is there a cleaner way to do this job?
Greetings
Fabian