简体   繁体   中英

How do i write float values to a file in f#

i tried this following code what did i do wrong?

// Test IO
// Write a test file
    let str : string[,] = Array2D.init 1 ASize (fun i j -> result.[i,j].ToString() ) 
    System.IO.File.WriteAllLines(@"test.txt", str );

Will the first argument to Array2D.init in your code always be 1? If yes, then you can just create one dimensional array and it will work just fine:

let str = Array.init ASize (fun j -> result.[0,j].ToString() )  
System.IO.File.WriteAllLines("test.txt", str ); 

If you really need to write a 2D array to a file, then you can convert 2D array into a one-dimensional array. The simplest way I can think of is this:

let separator = ""
let ar = Array.init (str.GetLength(0)) (fun i -> 
  seq { for j in 0 .. str.GetLength(1) - 1 -> str.[i, j] }
  |> String.concat separator )

This generates a one-dimensional array (along the first coordinate) and then aggregates the elements along the second coordinate. It uses String.concat , so you can specify separator between the items on a single line.

because there are no overloads of File.WriteAllLines that accepts 2d array of strings. You should either convert it to 1d array or to seq<string>.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM