About to!int

bearophile bearophileHUGS at lycos.com
Mon Jan 30 18:01:38 PST 2012


In Python int() and float() convert a string into a number even if it contains some whitespace before and after the number:


>>> s = " 12\n"
>>> int(s)
12
>>> float(s)
12.0


In D  to!int(" 12\n")  gives a run-time error. So time ago I have weakly asked Andrei to change to!int, to let it ignore leading and trailing whitespace, but he has ignored my request.

A leading newline comes often from input stdin.readln() and other sources. So in D you need to add a strip():

int n = to!int(stdin.readln().strip());

I sometimes forget to add the strip(). Do you know why Andrei has not appreciated the idea of to!int and similar functions to ignore leading and trailing whitespace?

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list