www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - "string" data type with readln

reply pascal111 <judas.the.messiah.111 gmail.com> writes:
I tried to type small program, and tried to use "string" data 
type with "readln", but the compiler refused it, and I had to use 
"char[]". So, if we can't use "string" with "readln", so what's 
its benefit? why we need to use it?

Code source:
https://github.com/pascal111-fra/D/blob/main/proj01.d
Jul 25 2022
next sibling parent Adam D Ruppe <destructionator gmail.com> writes:
On Monday, 25 July 2022 at 19:55:40 UTC, pascal111 wrote:
 I tried to type small program, and tried to use "string" data 
 type with "readln", but the compiler refused it, and I had to 
 use "char[]".
the overload you used modifies the array you give it try string s = readln();
Jul 25 2022
prev sibling parent rikki cattermole <rikki cattermole.co.nz> writes:
The version of readln you are using is[0]. This works by taking in a 
buffer of memory to write out, and returns how many codepoints were stored.

Because you are not reusing memory, not using this form you can of 
course use string[1] instead, rather than ``char[]``.

```d
string s = readln();
```

The definition of string is[2]:

```d
alias string  = immutable(char)[];
```

Note the immutable there, which means that each value in the slice 
cannot be modified. Hence why it can't be used as a buffer.

[0] https://dlang.org/phobos/std_stdio.html#.readln.2
[1] https://dlang.org/phobos/std_stdio.html#.readln
[2] https://github.com/dlang/dmd/blob/master/druntime/src/object.d#L69
Jul 25 2022