String.to_integer conversion

I am writing a program where I have to convert a string to an integer. If the conversion passes then the program should simply print true else false.

defp range([head | tail]) do
    integer = String.to_integer(head) # line 19

    cond do
      integer >= 0 and integer <= 255 ->
        range(tail)

      integer < 0 or integer > 255 ->
        false
    end
  end

In this program when I try to enter the string that is integers then it works fine. for example

Solution.is_valid_ip("123.42.123.33")
true

but when I insert any character then it shows an error. Is there any way that I can just print out false except the error message.

 Solution.is_valid_ip("123.a42.77.34")

** (ArgumentError) argument error
    :erlang.binary_to_integer("a42")
    ip.ex:19: Solution.range/1

Integer.parse vs. String.to_integer.

4 Likes

Thank you so much … it was a life saviour. So it works like this now

if Integer.parse("123a4") == :error do
    false
else
    true

and it works perfectly.