How to print the blank line in the file?

Hello,
The input.txt file is as follows:

1 2 3 4 5 6 7 8 9 10

11 12 13 14 15 16 17 18 19 20

The code below does not print the empty line:

inn = open("input.txt", "r")
inp = readline(inn)
while inp != ""
    println(inp)
    inp = readline(inn)
end

How to solve it?

Thank you.

You could do:

input = readlines("input.txt")
for line in input
    println(line)
end

Does that solve your issue?

1 Like

I’m pretty sure the ‘problem’ is that readline (with the default keep=false) gets rid of the newline characters, so that the second line, as stored in inp, is just "". Your while loop then stops, and you never run the println a second time. In particular, you do not print the empty line (or any line after that).

@ufechner7 's code does not have this issue, as the looping only stops when the input is completely exhausted.

1 Like

Hello,
I know that I can do this with the following code:

for line in eachline("input.txt")
    println(line)
end

But I am looking for a solution to fix my code problem.

Hello,
How to fix the problem?

Well, if you call readline and the line is empty you get an empty string back. So there is no way to determine if the end of the file was reached. OK, you could use readline(inn; keep=true) and then remove the trailing linefeed character manually.

  readline(io::IO=stdin; keep::Bool=false)
  readline(filename::AbstractString; keep::Bool=false)

  Read a single line of text from the given I/O stream or file (defaults to
  stdin). When reading from a file, the text is assumed to be encoded in
  UTF-8. Lines in the input end with '\n' or "\r\n" or the end of an input
  stream. When keep is false (as it is by default), these trailing newline
  characters are removed from the line before it is returned. When keep is
  true, they are returned as part of the line.

But you did not really explain what you want to achieve and why you do not want to use readlines(), so it is difficult to help you.

2 Likes

is this ok for you?

while inp != "" || !eof(inn)
    println(inp)
    inp = readline(inn)
end

or this form

begin
inn = open("inp.txt", "r")

while  !eof(inn) 
    inp = readline(inn)
    println(inp)
end
end
1 Like

The problem with your code is that you are stopping when you encounter an empty line, rather than stopping at the end of the file.

Your halting condition should probably be while !eof(inn) instead, which checks that you haven’t reached the end of the file (eof).

And you should then check this before calling readline, as otherwise you may not print the last line of the file. For example, similar to what @rocco_sprmnt21 posted above:

inn = open("input.txt", "r")
while !eof(inn)
    inp = readline(inn)
    println(inp)
end
close(inn)

As noted above, there are many other ways to do this, e.g. using eachline or readlines, but this is probably the closest to the spirit of how you are trying to write the code.

1 Like