Smartest way to read a number?

Fabian talk2fab at online.de
Thu Nov 10 13:48:30 PST 2011


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


More information about the Digitalmars-d-learn mailing list