code.go 709 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. )
  9. func readInput(file *os.File) []int {
  10. scanner := bufio.NewScanner(file)
  11. numbers := []int{0}
  12. index := 0
  13. for scanner.Scan() {
  14. line := scanner.Text()
  15. if line == "" {
  16. index++
  17. numbers = append(numbers, 0)
  18. continue
  19. }
  20. if number, err := strconv.Atoi(line); err == nil {
  21. numbers[index] += number
  22. } else {
  23. log.Fatal("Numbers: ", err)
  24. }
  25. }
  26. return numbers
  27. }
  28. func main() {
  29. if len(os.Args) < 2 {
  30. log.Fatal("You need to specify a file!")
  31. }
  32. filePath := os.Args[1]
  33. file, err := os.Open(filePath)
  34. if err != nil {
  35. log.Fatalf("Failed to open %s!\n", filePath)
  36. }
  37. numbers := readInput(file)
  38. fmt.Println(numbers)
  39. }