Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ocaml string to 4 floats

I'm trying to get the floats from a string. I mean reading line by line from a text file and getting the floats from a line. I found how to read line by line but I couldn't split the string into floats. Here is an example input file:

10,10,18,18.1

7,3 ,10,14.2

3,3,5.3,5

I've looked at sscanf but I couldn't do it. Any idea?

like image 354
bleda Avatar asked Mar 09 '12 00:03

bleda


2 Answers

From years of experience, I've found that scanf is unlikely to do exactly what you want. It's OK for a quick test program.

One possibility is to use Str.split:

let floats_of_string s =
    List.map float_of_string (Str.split (Str.regexp "[, \t]+") s)

You might need to make the regexp a little tighter if you want to detect invalid input.

like image 152
Jeffrey Scofield Avatar answered Oct 14 '22 00:10

Jeffrey Scofield


Read the manual attentively to understand how scanf format works - it has some quirks but there is a reason behind them.

"%f , %f , %f , %f %!"
like image 43
ygrek Avatar answered Oct 13 '22 23:10

ygrek