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

如何在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条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥20 【matlab】运输问题优化问题。
      • ¥15 arduino连接WiFi8266
      • ¥15 nodejs express 和 axios 前后端对接,数据体类型
      • ¥15 fluent计算后处理中如何把质量分数和摩尔分数转化为体积分数
      • ¥20 asn1c编码问题,懂asn1的人很简单
      • ¥15 使用vs2019开发的动态链路库在win7环境下使用有问题
      • ¥15 MFC滚动条如何正确使用
      • ¥15 缓冲区算法求面积,基于文献
      • ¥50 电路PCB原理图设计AD19
      • ¥15 openstack 云平台搭建 创建实例错误