Ocaml string up to 4 floats

I am trying to get floats from a string. I mean reading line by line from a text file and getting floats from a line. I found how to read line by line, but I could not break the line into floats. Here is an example input file:

10,10,18,18.1

7.3, 10.14.2

3,3,5.3,5

I looked at sscanf, but I could not do it. Any idea?

+6
source share
2 answers

From years of experience, I have found that scanf is unlikely to do exactly what you want. This is normal 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 may need to make regexp a little tougher if you want to detect invalid input.

+8
source

Read the manual carefully to understand how scanf works - it has some quirks, but there is a reason for them.

 "%f , %f , %f , %f %!" 
+6
source

Source: https://habr.com/ru/post/910299/


All Articles