Go言語で電卓を作ってみた

Go言語で電卓を作ってみました. 四則演算限定でエラーチェックも中途半端なやっつけ.

package main

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

func main() {
  s := bufio.NewScanner(os.Stdin)
  for s.Scan() {
    token := strings.Split(s.Text(), " ")/* split token */
    num1, error := strconv.Atoi(token[1])
    if error != nil {
      fmt.Println("Erorr")
      os.Exit(1)
    }

    num2, error := strconv.Atoi(token[2])
    if error != nil {
      fmt.Println("Erorr")
      os.Exit(1)
    }

    if strings.EqualFold(token[0], "+") {
      fmt.Println(num1 + num2)
    } else if strings.EqualFold(token[0], "-") {
      fmt.Println(num1 - num2)
    } else if strings.EqualFold(token[0], "*") {
      fmt.Println(num1 * num2)
    } else if strings.EqualFold(token[0], "/") {
      fmt.Println(num1 / num2)
    } else {
      fmt.Println("error")
      os.Exit(1)
    }
  }
}

入力例

+ 3 4

出力

7