readln with buffer fails
dcrepid via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Oct 29 16:10:10 PDT 2014
On Wednesday, 29 October 2014 at 21:19:25 UTC, Peter Alexander
wrote:
> You need to take a slice of the buffer:
>
> char[] buf = Input[];
> readln(buf);
> // line now in buf
>
> The reason for this is because you need to know where the
> string ends. If you just passed in Input, how would you know
> how long the line read was?
Thanks, that solves the problem. I guess what confuses me is
that Input isn't a slice, or at least not implicitly convertible
to one.
Also, I've tried using Input[] directly at the callsite but
apparently that would be an rValue, and D doesn't do rValues yet.
So here's a simple solution to reading a line using a fixed stack
array:
char[4096] Input;
char[] InputSlice; // actual slice of input'd text (instead
of full 4K)
size_t NumChars;
while (NumChars == 0)
{
// readln(buf) requires a slice. Input isn't converted to
one,
// and readln() requires an rvalue for a buffer:
char[] buf = Input[];
NumChars = readln(buf);
// Set InputSlice to range of text that was input, minus
linefeed:
InputSlice = chomp(buf[0 .. NumChars]);
// Empty line?
if (InputSlice == "")
NumChars = 0;
}
Thanks all for your help
More information about the Digitalmars-d-learn
mailing list