Bug 4165 – std.conv.to!int doesn't ignore whitespace

Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-05-09T05:20:00Z
Last change time
2015-06-09T05:13:44Z
Assigned to
nobody
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2010-05-09T05:20:45Z
Too much flexibility in a language and its libs causes several problems, but the opposite too makes the language and its use fussy. So there is a right intermediate point of balance to be found. The conversion from string to numbers performed by std.conv.to is excessively rigid. In Python this conversion works: >>> int(" 0123\n") 123 In D v.2.043 the same produces an error: import std.conv: to; void main() { int x = to!int(" 0123\n"); } std.conv.ConvError: Can't convert value ` 0123 ' of type const(char)[] to type int Can std.conv.to be modified to ignore whitespace? In particular the ending newline is very common, for example every time I want to convert a line from a text file to a number I have to use something like this: to!int(readln().chomp()); Instead of a simpler: to!int(readln());
Comment #1 by bearophile_hugs — 2010-05-22T14:24:20Z
A comment by Adam Ruppe: > I don't think that's a bug. It should only worry about converting, not > filtering out bad stuff. That's an orthogonal problem that the other > function does well, and easily too. It's not a bug. But saying it's an orthogonal problem is not enough. You must keep a balance between having a so flexible language/stdlib that's sloppy and can lead to bugs, and to have as much orthogonal functions as possible that are fussy and can lead to opposite kinds of bugs. Often if I have to convert strings to numbers that have a leading newline. Converting such string with leading newline to a number is not sloppiness because my experience shows me it doesn't cause bugs in Python. The way to!() is currently designed forces me to remove the spaces often. This has caused a bug in one script-like D program.
Comment #2 by bugzilla — 2010-08-13T03:27:02Z
Since we all agree this is not a bug, I'm marking it as an enhancement request.
Comment #3 by dsimcha — 2010-08-15T08:10:52Z
I'm marking this as wontfix because it's by design (it's mentioned in the docs of std.conv), and there's a trivial workaround: int x = to!int(" 0123\n".strip());