Question

When executing:

def guess(a..b) do
  IO.puts "In rn = #{a}..#{b}"
  guess(a..b, IO.getn("Is it greater than #{div(a + b, 2)} ? : ", 1) |> String.upcase == "Y")
end
def guess(a..b, true) do
  guess(div(a + b, 2)..b)
end
def guess(a..b, false) do
  guess(a..div(a + b, 2))
end

Results:

iex(1)> Test.guess(1..10)
  1 In rn = 1..10
  2 Is it greater than 5 ? : y
  3 In rn = 5..10
  4 Is it greater than 7 ? :
  5 In rn = 5..7
  6 Is it greater than 6 ? : n
  7 In rn = 5..6
  8 Is it greater than 5 ? :
  9 In rn = 5..5
 10 Is it greater than 5 ? : y
 11 In rn = 5..5
 12 Is it greater than 5 ? :
 13 In rn = 5..5
 14 Is it greater than 5 ? :

iex did not wait for user input on lines 4, 8, & 12 - after receiving an input, it appears to run through the loop twice.

Why might that be?


Solved:

Apparently, something weird happens with IO.getn when used in this manner - perhaps reading "Y" as a byte, and "enter" as a separate byte. Replacing IO.gets and no character count seems to fix the problem. Alternatively, isolating the getn method call might keep this issue from occurring.

Was it helpful?

Solution

You are correct. When in the terminal, IO.getn/1 only returns the bytes after you enter a new line, which means if you are reading byte per byte recursively, you are going to receive two bytes, one for the user command and another for the new line. IO.gets/1 is the way to go here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top