Reading a line from stdin

spir denis.spir at gmail.com
Wed Mar 16 03:09:24 PDT 2011


On 03/16/2011 06:05 AM, 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

This is a design bug. 99% of the time one does not want the newline, which is 
not part of the string data, instead just a terminator. Even more on stdin 
where it is used by the user to say "I"m done!".
If the text is written back to the output /and/ newline is needed, it's easy to 
add it or use writeln.

Also, to avoid using strip --which is costly and may remove other significant 
whitespace at start and end of line, one would have to manually check for CR 
and/or LF, and remove it, *twice*. A solution may be to have a boolean param 
"keepNewLine" beeing false in standard.

> 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?

Dunno.

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list