From 9d94781daeaf6e8f8c5a2cf6a4c5c1e17116e198 Mon Sep 17 00:00:00 2001 From: DutchEllie Date: Wed, 8 Dec 2021 11:12:34 +0100 Subject: [PATCH] Reading numbers --- 7-1/main.go | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/7-1/main.go b/7-1/main.go index e354c43..be75740 100644 --- a/7-1/main.go +++ b/7-1/main.go @@ -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 }