Fixing a program that parses flags

Report a typo

Kendrick has been learning about Go flags; he's decided to create a small Go program that works as a very simple calculator. It takes three flags: --num1, --operator and --num2:

package main

import (
    "flag"
    "fmt"
    "log"
)

func main() {
    num1 := flag.Float64("num1", 1, "Enter the first number")
    operator := flag.String("operator", "+", "Enter one of the operators: +, -, *, /")
    num2 := flag.Float64("num2", 1, "Enter the second number")

    // What should we do after declaring all the flags? The entered code line will go here!

    switch *operator {
    case "+":
        fmt.Printf("%.2f + %.2f = %.2f\n", *num1, *num2, *num1 + *num2)
    case "-":
        fmt.Printf("%.2f - %.2f = %.2f\n", *num1, *num2, *num1 - *num2)
    case "*":
        fmt.Printf("%.2f * %.2f = %.2f\n", *num1, *num2, *num1 * *num2)
    case "/":
        fmt.Printf("%.2f / %.2f = %.2f\n", *num1, *num2, *num1 / *num2)
    default:
        log.Fatal("Error! Invalid math operator.")
    }
}

Kendrick has tried to execute the program passing flags and arguments; however, he hasn't got the expected output! Instead, he has got the default values of flags:

$ ./main --num1 1.61 --operator "*" --num2 3.14

1.00 + 1.00 = 2.00

Please help Kendrick fix his code by entering the missing line required to properly parse flags from the command line below:

Enter a short text
___

Create a free account to access the full topic