douhuan7862 2018-06-16 08:32
浏览 38
已采纳

Scanf值在终端中作为命令执行

I have simple go program that converts miles to kilometers:

const kmInMile = 1.609344

func main() {
    var miles float64

    fmt.Print("Enter miles: ")
    fmt.Scanf("%f", &miles)

    fmt.Println(miles)

    km := kmInMile * miles

    fmt.Println(miles, "miles =", km, "km")
}

If I pass "lls" as input to scanf:

Enter miles: lls

Output is:

0
0 miles = 0 km
alexandrkrivosheev$ ls
hello   main.go

so the first char of input was taken and all other were executed as command. Why does it happened and how can i prevent this?

Full terminal session:

alexandrkrivosheev$ ./hello 
Enter miles: lls
0
0 miles = 0 km
alexandrkrivosheev$ ls
hello   main.go
alexandrkrivosheev$ 
  • 写回答

1条回答 默认 最新

  • douchunxian9740 2018-06-16 09:39
    关注

    When using "plain fmt.Scanf" the input must match the expected format, ie in your case it must be valid float. If it isn't then the scanning is aborted and rest of the input remains in console's input buffer where it is executed as next command after your program exits.

    To fix this you wrap the stdin into an bufio.Reader or bufio.Scanner:

    func main() {
        var miles float64
    
        fmt.Print("Enter miles: ")
        //
        reader := bufio.NewReader(os.Stdin)
        val, err := reader.ReadString('
    ')
        if err != nil {
            fmt.Println(err)
            return
        }
        if _, err = fmt.Sscanf(val, "%f", &miles); err != nil {
            fmt.Println(val, err)
            return
        }
    
        fmt.Println(miles)
    
        km := kmInMile * miles
    
        fmt.Println(miles, "miles =", km, "km")
    }
    

    This way you consume whole line from input and process it separately.

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

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b