print ubyte[] as (ascii) string

Steven Schveighoffer schveiguy at gmail.com
Mon Jan 3 02:50:46 UTC 2022


On 1/2/22 4:15 AM, eugene wrote:
> On Sunday, 2 January 2022 at 08:39:57 UTC, eugene wrote:
>> ```d
>> import std.stdio;
>> import std.string;
>> ```
> 
> oops...
> 
> ```d
> import std.stdio;
> import std.string;
> import std.algorithm : until;
> 
> void main() {
>      ubyte[8] b = [0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x0A, 0x00, 0x00];
>      /* "hello\n\0\0" */
>      writefln("'%s, world'", cast(char[])b[].until('\n'));
> }
> 
> ```
> 
> ```
> p1.d(9): Error: cannot cast expression `until(b[], '\x0a', Flag.yes)` of 
> type `Until!("a == b", ubyte[], char)` to `char[]`
> 
> ```
> 

Thanks for posting the entire example, that always helps to diagnose 
unexpected errors.

You missed a set of parentheses. `cast` is quite low for operator 
precedence.

What is happening in your code is:

`b[].until('\n')` is being evaluated *first*, which returns an 
`Until!...` struct, which then cannot be cast into char[].

But if you run my code, I do `(cast(char[])b[]).until('\n')`, which 
*first* casts the ubyte array into a char array, and *then* runs `until` 
on it.

-Steve


More information about the Digitalmars-d-learn mailing list