Reading numbers

This commit is contained in:
DutchEllie 2021-12-08 11:12:34 +01:00
parent 7d7ff0ed1d
commit 9d94781dae
1 changed files with 56 additions and 2 deletions

View File

@ -1,7 +1,61 @@
package main
import "fmt"
import (
"bufio"
"bytes"
"fmt"
"os"
"strconv"
)
func main() {
fmt.Printf("Hello world!\n")
numbers, err := readInput("input")
if err != nil {
fmt.Printf("Error encountered: %s", err)
return
}
}
func readInput(inputfile string) ([]int, error) {
file, err := os.OpenFile(inputfile, 0, 0)
if err != nil {
return nil, err
}
defer file.Close()
splitfunc := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
nextIndex := bytes.IndexByte(data, ',')
if nextIndex > 0 {
// Returning the next position aka taking only the stuff up to nextIndex and slicing off everything else
buffer := data[:nextIndex]
// nextIndex plus 1 because index is at the comma, we want the next number
return nextIndex + 1, bytes.TrimSpace(buffer), nil
}
// If we are at the end of the buffer, then return the entire buffer, but only if there is data
if atEOF {
if len(data) > 0 {
return len(data), bytes.TrimSpace(data), nil
}
}
// https://github.com/kgrz/reading-files-in-go/blob/master/comma-separated-string.go
// For more info
return 0, nil, nil
}
scanner := bufio.NewScanner(file)
scanner.Split(splitfunc)
numbers := make([]int, 0)
for scanner.Scan() {
number, err := strconv.Atoi(scanner.Text())
if err != nil {
fmt.Printf("Error converting string to integer\n")
return nil, err
}
numbers = append(numbers, number)
}
return numbers, nil
}