Answer the question
In order to leave comments, you need to log in
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
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
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question