readln() returns new line charater

Jakob Ovrum jakobovrum at gmail.com
Sat Dec 28 09:09:49 PST 2013


On Saturday, 28 December 2013 at 16:50:21 UTC, Jeroen Bollen 
wrote:
> On Saturday, 28 December 2013 at 16:49:15 UTC, Jeroen Bollen 
> wrote:
>> Why is when you do readln() the newline character (\n) gets 
>> read too? Wouldn't it make more sense for that character to be 
>> stripped off?
>
> I just want to add to this, that it makes it really annoying to 
> work with the command line, as you kinda have to strip off the 
> last character and thus cannot make the string immutable.

It doesn't stop you from stripping off the last character. 
Assuming that you're using the nullary overload of `readln`: the 
return type is `string`, which is an alias of 
`immutable(char)[]`, which is a mutable slice of immutable 
characters:
---
void main()
{
     import std.stdio;

     auto line = readln();
     if (line.length != 0) // Standard input had data
     {
         line = line[0 .. $ - 1]; // Slice off EOL
         writefln(`got line: "%s"`, line);
     }
}

---
Writing to the characters in `line` is not permitted as they are 
immutable, but slicing `line`, as well as reassigning `line` to a 
different slice, is perfectly fine because the slice itself is 
mutable. `immutable(char[])` would be the type where both the 
characters and the slice are immutable.

If you also wanted to strip any trailing whitespace on the line 
from standard input, you could use `line = line.stripRight();` - 
where `stripRight` is from std.string - to do both at once.


More information about the Digitalmars-d mailing list