sudo
sudo

Reputation: 5784

Erlang string:to_integer/1 failing to parse valid string

I'm trying to read a text file that contains a integer represented in ASCII (for example, "2446") and parse that into an integer in my Erlang/OTP program. string:to_integer/1 always returns {error, no_integer} when I try to parse "1". Perhaps I made a beginner's mistake. What am I doing wrong? Here's the relevant code, where I try to set Index to the integer:

Index = case file:read_file(Indexpath) of
        {ok, Binary} ->
            Index2 = case string:to_integer(io_lib:format("~s", [Binary])) of
                {error, Reason} ->
                    io:format("to_integer error from input ~s: ~s~n", [Binary, Reason]),
                    0;
                {Index3, _} -> Index3
            end,
            Index2;
        {error, _} ->
            Index2 = 0,
            ok = file:write_file(Indexpath, io_lib:format("~B", [Index2+1])),
            Index2;
        _ ->
            io:format("read_file case didn't match!~n", []),
            -1
    end,

What gets printed to the console when I run this: to_integer error from input 1: no_integer Clearly, the input is the string "1", so I don't understand why this happens. If I do a little test case,

Indexstr = "4", string:to_integer(Indexstr).

that returns {4, []} as expected.

Upvotes: 0

Views: 233

Answers (2)

Viacheslav Kovalev
Viacheslav Kovalev

Reputation: 1745

This is because io_lib:format/2 returns iolist (similar to deep list) instead of flat one. You can find iolist definition here. Moreover, in new versions of erlang (starting from R16) you can use function `erlang:binary_to_integer/1' to avoid intermediate conversions.

Upvotes: 2

sudo
sudo

Reputation: 5784

Found the answer as I was typing the question. I replaced

string:to_integer(io_lib:format("~s", [Binary]))

with

string:to_integer(binary_to_list(Binary))

Upvotes: 1

Related Questions