2

I have written a simple calculate for example but it isnot work

a = IO.gets"a = "
a = String.to_integer(a)
b = IO.gets"b = "
b = String.to_integer(b)
v = a + b
IO.puts "Sum: #{v}"

How can I correct this code?

1 Answer 1

4

IO.gets does not trim the trailing newline character which makes String.to_integer fail even if you enter only digits. You can remove it using String.trim_trailing/1:

a = IO.gets("a = ") |> String.trim_trailing
a = String.to_integer(a)
b = IO.gets("b = ") |> String.trim_trailing
b = String.to_integer(b)
v = a + b
IO.puts "Sum: #{v}"
$ elixir a.exs
a = 123
b = 456
Sum: 579
Sign up to request clarification or add additional context in comments.

1 Comment

a = "a = " |> IO.gets() |> String.trim_trailing() |> String.to_integer() looks more elixirish :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.