I
I
impressive172020-01-19 15:36:15
go
impressive17, 2020-01-19 15:36:15

How to read int from file and put into GO slice?

There is a file. It has a number on each line. You need to count them and put them into a slice []int. How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2020-01-19
@impressive17

the code
package main

import (
  "bufio"
  "fmt"
  "io"
  "log"
  "os"
  "strconv"
)

func main() {
  r, err := os.Open("file.txt")
  if err != nil {
    log.Fatal(err)
  }
  defer r.Close()

  s, err := linesToInt(r)
  if err != nil {
    log.Fatal(err)
  }

  fmt.Println(s)
}

func linesToInt(r io.Reader) ([]int, error) {
  var arr []int
  s := bufio.NewScanner(r)
  for s.Scan() {
    text := s.Text()

    i, err := strconv.Atoi(text)
    if err != nil {
      continue
    }

    arr = append(arr, i)
  }

  err := s.Err()
  if err != nil {
    return nil, err
  }

  return arr, nil
}

https://play.golang.org/p/dSvP6rzv4s3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question