How to parse a file on Go There is a file with a view matrix

3 1.01 1.02 6.3 ....... 5.343 2.04 1.03 3.3 ....... 5.343 ........................... ........................... 2.3 ................... 4.5 

Where the top line is the dimension of the matrix, and all other lines are matrices. It is necessary to parse into a double array of the form var a [] [] Float64

  • no ideas at all? - user227465
  • Dimension three, and the final matrix 5x5? Give at least a normal example file and what should come out of it. - Ainar-G
  • You can start here . This is not exactly your task, but very similar. Especially interesting option from peterSO. Good luck. - biosckon

1 answer 1

Your input data is not completely clear, but if it is assumed that they are correct and look something like this

 3 1.0 2.1 3.4 2.1 3.2 3.3 1.5 3.2 1.1 

then the solution in the forehead looks something like this

 file, err := os.Open("file") if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) // get size scanner.Scan() N, err := strconv.Atoi(scanner.Text()) if err != nil { panic(err) } // init matrix matrix := make([][]float64, N) for i := 0; i < N; i++ { matrix[i] = make([]float64, 0, N) } // scan values from the file i := 0 for scanner.Scan() { ar := strings.Split(scanner.Text(), " ") for _, a := range ar { val, err := strconv.ParseFloat(a, 64) if err != nil { panic(err) } matrix[i] = append(matrix[i], val) } i++ } // print matrix for _, line := range matrix { fmt.Println(line) }