1
\$\begingroup\$

I have to write a code which takes (integers) numbers from Command-line and keeps reading the terminal until it gets a word END

So I wrote the following; I feel its really bad. Is there any way I can improve below code

I updated my code from previously to below

func main() {
    buf := bufio.NewReader(os.Stdin)
    lines, err := buf.ReadBytes('\n')

    if err != nil {
        return
    }

    fmt.Printf(" %q \n", string(lines))
    line := strings.Replace(string(lines), "\n", "", -1)

    numbers := strings.Split(line, " ")
    fmt.Printf("numbers %q ", numbers)
    var sum int64
    for _, num := range numbers {
        num, err := strconv.ParseInt(num, 10, 0)
        if err != nil {
            fmt.Println(err)
            break
        }
        sum += num
    }
    fmt.Println("Sum of all numbers :", sum)

}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

takes (integers) numbers from Command-line and keeps reading the terminal until it gets a word END.


For example,

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    sum := int64(0)
    s := bufio.NewScanner(os.Stdin)
    s.Split(bufio.ScanWords)
    for s.Scan() {
        word := s.Text()
        num, err := strconv.ParseInt(word, 10, 64)
        if err != nil {
            if strings.ToUpper(word) == "END" {
                break
            }
            fmt.Fprintln(os.Stderr, err)
            continue
        }
        sum += num
    }
    if err := s.Err(); err != nil {
        fmt.Fprintln(os.Stderr, err)
    }
    fmt.Println("Sum of all numbers:", sum)
}

Terminal:

12 24 
36 
6
6
  END
Sum of all numbers: 84
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.