drbl91357 2017-01-20 05:13
浏览 101
已采纳

如何在Go中使用Cobra库在单行中接受输入

I am writing a code in go language using cobra, currently the input Im giving is :

 Calc add 
           Enter the Number of inputs
           2
           Enter the Numbers
           2
           4
 Output: Sum is : 6

In this those who are familiar with cobra, Calc is my project and add is the command Im using,I want the input to be given as Calc add N2 2 4( in a single line) and the output should be displayed, where N is a variable that identifies the Number of inputs and 2 4 are the numbers to be added.

CODE FOR THE ADD COMMAND:

package cmd

import (
    "fmt"

    "github.com/spf13/cobra"
)

// addCmd represents the add command
var addCmd = &cobra.Command{
    Use:   "add",
    Short: "Addition value of given Numbers",

    Run: func(cmd *cobra.Command, args []string) {
        length := 0
    fmt.Println("Enter the number of inputs")
    fmt.Scanln(&length)
    fmt.Println("Enter the inputs")
    numbers := make([]int, length)
    for i := 0; i < length; i++ {
        fmt.Scanln(&numbers[i])
    }
      fmt.Println(numbers)

      sum:=0

for _, numbers := range numbers {

sum += numbers

}

fmt.Println("The Sum :",sum)


 },
}

func init() {
    RootCmd.AddCommand(addCmd)


}

P

  • 写回答

1条回答 默认 最新

  • 普通网友 2017-01-20 10:30
    关注

    This will fulfill your purpose. Take your number in a flag --input. Give other numbers to add as arguments.

    func NewCmd() *cobra.Command {
        var input int
        c := &cobra.Command{
            Use:   "add",
            Short: "Addition value of given Numbers",
    
            Run: func(cmd *cobra.Command, args []string) {
                if len(args) != input {
                    fmt.Println(fmt.Sprintf("You need to provide %v number to sum up", input))
                    os.Exit(1)
                }
                numbers := make([]int, input)
                for i := 0; i < input; i++ {
                    num, _ := strconv.Atoi(args[i])
                    numbers[i] = num
                }
                sum := 0
                for _, numbers := range numbers {
                    sum += numbers
                }
                fmt.Println("The Sum :", sum)
            },
        }
        c.Flags().IntVar(&input, "input", 0, "Number of input")
        return c
    }
    
    func init() {
        cmd := NewCmd()
        RootCmd.AddCommand(cmd)
    }
    

    Input:

    Calc add --input=3 6 3 6
    

    Output: The Sum : 15

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题