Main foreach loop fails when another foreach is added

Steven Schveighoffer schveiguy at gmail.com
Mon Aug 8 02:45:54 UTC 2022


On 8/7/22 10:11 PM, ikelaiah wrote:
> Hi,
> 
> I'm writing a program that reads a text file and launch my work URLs in it.
> It worked fine, and very happy.
> 
> Then I added another `foreach` loop to count total number of lines.
> After this, the main `foreach` won't work.
> 
> Does anyone know as to why this happens?
> I might have missed something very obvious.
> 
> Thank you.

> 
> ```d

...

>      // Open input file for reading
>      size_t line_count = 0;
>      File input_file = File(input_filename);

Here you open the file

>      auto file_range = input_file.byLine(KeepTerminator.no, 
> std.ascii.newline);

And then wrap it in a byline range.

> 
>      // if this foreach not commented out
>      // the last foreach won't run.
>      foreach (char[] line; file_range)
>      {
>          line_count += 1;
>      }

For this foreach loop, you read every line in the file, exhausting the 
file (the input stream for the file is empty).

> 
>      // the MAIN foreach loop
>      // -- won't run if above foreach is enabled
>      foreach (char[] line; file_range)
>      {
>          if (!line.empty)
>          {
>              writeln("Open URL: " ~ line);
>              Thread.sleep(dur!("seconds")(2));
>              browse(line);
>          }
>      }

And now, you tried to read it again! Which means you are trying to read 
more data from an empty stream.

You need to either a) reopen the file, or b) do both in the same loop.

> ```

-Steve


More information about the Digitalmars-d-learn mailing list