Does Elixir have the equivalent functionality of scanf?

Does Elixir have the equivalent functionality of scanf? How would I accomplish scanf “%d %f %s\n” in Elixir?

1 Like

The only option I know of really, is io:fread:

http://erlang.org/doc/man/io.html#fread-2

You’d use it like this:

iex(22)> :io.fread('Enter data: ', '~d ~f ~s')                    
Enter data: 14 3.211e3 Foo
{:ok, [14, 3211.0, 'Foo']}
iex(23)> :io.fread('Enter data: ', '~d ~f ~s')                    
Enter data: 14 3211 Foo                          
{:error, {:fread, :float}}
iex(24)> :io.fread('Enter data: ', '~d ~f ~s')
Enter data: Bar 3.211e3 Foo                      
{:error, {:fread, :integer}}

Note that to read UTF-8, you must pass the ‘t’ modifier to the string field, and just as with regular strings from Erlang functions it’ll be in the list format instead of a binary, so you’ll want to convert it:

iex(28)> {:ok, [x, y, z]} = :io.fread('Enter data: ', '~d ~f ~ts')
Enter data: 14 3.211e3 Foo☂                                          
{:ok, [14, 3211.0, [70, 111, 111, 9730]]}
iex(29)> List.to_string(z)                                        
"Foo☂"
2 Likes

Ahhh, That would explain why I couldn’t find it in the Elixir docs. Thanks.

1 Like

If you want something more powerful as well, there is the Combine library. :slight_smile:

1 Like