Convert a string to an integer?

Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from a string to an int. Any help would be greatly appreciated.

Hi there!

To convert a string to an integer you can use String.to_integer/1 e.g.

int = String.to_integer("1")

When it comes to user input you might also want to remove whitespace first which you can do with String.trim/1.

Hope that helps!

2 Likes
defmodule GuessingGame do
def hello do

    IO.puts("Welcome to the number guessing game!!!")
    IO.puts("--------------------------------------")
    user_input = IO.gets ("What is your guess? ")
    :string.to_integer(user_input)

    IO.puts("--------------------------------------")
  random_num = :rand.uniform(1)
  IO.puts("The random number was #{random_num} ")


  cond do

  random_num === user_input ->
      "Correct Guess"
  random_num != user_input ->
        "Incorrect Guess"
end
end
end

Sorry, I was having trouble with my wifi. Here is my code

Edited for code blocks. I recommend formatting code that you post, it helps others understand what’s going on to help you better.

In your case you wrote :string.to_integer but @tyro wrote String.to_integer. Elixir module names capitalized, erlang modules tend to be lower case. That’s why :rand.uniform uses lower case :rand, it’s an erlang module. String however is an Elixir module, you can find the documentation on it here: https://hexdocs.pm/elixir/String.html

1 Like
> defmodule GuessingGame do
> def hello do

>     IO.puts("Welcome to the number guessing game!!!")
>     IO.puts("--------------------------------------")
>     user_input = IO.gets ("What is your guess? ")
>     num = String.to_integer(user_input)

>     IO.puts("--------------------------------------")
>   random_num = Enum.random([1, 2, 3, 4, 5])
>   IO.puts("The random number was #{random_num} ")


>   cond do

>   random_num === num ->
>       "Correct Guess"
>   random_num != num ->
>         "Incorrect Guess"
> end
> end
> end

I am new to this. Not working yet. Am I close?

As @tyro mentioned you should pass user_input through String.trim/1 to remove the "\n" at the end of it.

num = user_input |> String.trim |> String.to_integer

You also don’t need the === in this case, == will suffice.

I appreciate the help. Thanks