Smartest way to read a number?
Jonathan M Davis
jmdavisProg at gmx.com
Thu Nov 10 14:17:01 PST 2011
On Thursday, November 10, 2011 13:48 Fabian 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?
parse already throws an exception if it can't parse anything. There's no need
to call isNumeric and throw an exception yourself. However, if you want to
guarantee that the whole string is a valid number instead of just the
beginning (parse parses as much as it can, leaving what it can't in the
string, and throwing if it couldn't parse anything), then use std.conv.to. It
requires that the string be _exactly_ a number (no whitespace or extraneous
characters). It also doesn't consume the string at all (since it's converting
all or nothing).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list