Reading a line from stdin

Jonathan M Davis jmdavisProg at gmx.com
Tue Mar 15 23:04:33 PDT 2011


On Tuesday 15 March 2011 22:05:37 Ali Çehreli wrote:
> I am going over some sample programs in a text of mine and replacing
> std.cstream references with std.stdio. There are non-trivial differences
> with formatted input.
> 
> The following program may be surprising to the novice:
> 
> import std.stdio;
> 
> void main()
> {
>      write("What is your name? ");
>      string name = readln();
>      writeln("Hi ", name, "!");
> }
> 
> The newline character is read as a part of the input:
> 
> What is your name? Ali
> Hi Ali
> !       <-- this is outputted on the next line
>              because of the newline character
> 
> A solution is to strip the line after reading:
> 
> import std.string;
> // ...
>      string name = strip(readln());
> 
> Right? Is there a better way that I am missing?

I don't think that it's all that odd from the newline to be left in. It _was_ in 
the original input, after all. I don't recall what the typical thing to do is in 
other languages though, since I don't do a lot with input from stdin. I can 
understand why you would think that it's odd, but I think that it's fine as is. 
It's a matter of preference really, and as Jesse points out, it's easier to just 
leave it in and allow the programmer to remove it than to remove it and make the 
programmer put it back if they want it (especially since that would require a 
reallocation whereas the other does not).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list