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.

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

报告相同问题?

悬赏问题

  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题