-2

I am brand new to the Go programming language and I am trying to build a very simple calculator. The issues I am running into is if someone enters in 4+2 or 5/10 or 100-25 to the command line how do I grab the operator and operands out of this string in order to perform the equation?

This is what I have so far, but this just grabs the entire string

package main

import (
"bufio"
"fmt"
"os"
"stack" //stack code works perfectly
)

func main() {

// Read a line from stdin.
scanner := bufio.NewScanner(os.Stdin)

for scanner.Scan() {
    line := scanner.Text()
    // fmt.Println(line)

    //Separate the string based on operator and operands

    // Push all of the characters onto the stack.
    s := stack.New()
    for i := 0; i < len(line); i++ {
        if err := s.Push(line[i]); err != nil {
            panic("Push failed")
        }
    }
ain
  • 22,394
  • 3
  • 54
  • 74
  • 1
    please provide as much as possible code that can be compiled. Use the https://play.golang.org to make sure things are working. – k1m190r Nov 15 '17 at 16:49
  • 1
    Have you made any attempt to actually parse the string you're getting? This question, as it stands, is basically asking for an entire implementation. – Adrian Nov 15 '17 at 17:06
  • This might help you: [How to evaluate an infix expression in just one scan using stacks?](https://stackoverflow.com/questions/13421424/how-to-evaluate-an-infix-expression-in-just-one-scan-using-stacks). It's not an implementation, but it has the logic. – tgogos Nov 15 '17 at 17:11

1 Answers1

0

Some pointers for you.

  1. To get operands from your line try strings.FieldsFunc().
  2. Convert your operands to float64 try strconv.ParseFloat() or fmt.Sscanf().
  3. Figure out what operation +, -, /, * you have. Perhaps with strings.ContainsRune().
  4. Perform operation on operands and present results.
  5. Have fun!
k1m190r
  • 1,213
  • 15
  • 26