Go程序在Windows 7上无法工作。

huangapple go评论72阅读模式
英文:

Go Program not working in WIndows 7

问题

我正在使用这个程序创建一个单链表,并打印链表的元素。在我的 Mac 上它能正常工作,但是当我尝试在 Windows 7 上运行相同的程序时,它没有按预期工作。有人能找出问题所在吗?

// 创建一个单链表并显示链表的元素
package main

import "fmt"

// 节点结构
type Node struct {
    Value int
    Next  *Node
}

func main() {
    var value int
    var head, current *Node

    // 创建链表
    for i := 0; i <= 5; i++ {
        fmt.Print("请输入一个数字:")
        fmt.Scanf("%d", &value)

        var newNode = &Node{value, nil}
        if head != nil {
            current.Next = newNode
        } else {
            head = newNode
        }
        current = newNode
    }

    // 打印链表的元素
    for node := head; node != nil; node = node.Next {
        fmt.Printf("%d ", node.Value)
    }
}

输出:

E:\go > go run linked_list.go
请输入一个数字:10
请输入一个数字:请输入一个数字:20
请输入一个数字:请输入一个数字:30
请输入一个数字:10 20 20 30 30 30

这段代码创建了一个单链表,并从用户输入中获取元素的值。然后,它遍历链表并打印出每个节点的值。根据你提供的输出,程序似乎没有按预期工作。可能的问题是在输入数字时出现了错误,导致链表中的重复元素。你可以检查一下输入部分的代码,确保输入的数字没有重复。

英文:

I am using this program to create a single linked list and print elements of list. Its working in my Mac but when I try same program in Windows 7 its not working as expected. Can someone identify what is issue here?

// Create a single linked list and display elements of list
package main

import &quot;fmt&quot;

// Node structure
type Node struct {
    Value int
    Next *Node
}

func main() {
    var value int
    var head, current *Node

    // Create linked list
    for i := 0; i &lt;= 5; i++ {
	   fmt.Print(&quot;Plase enter a number: &quot;)
	   fmt.Scanf(&quot;%d&quot;, &amp;value)

	   var newNode = &amp;Node{value, nil}
	   if head != nil {
	      current.Next = newNode
	   } else {
		  head = newNode
	   }
	   current = newNode
    }

    // Print elements of linked list
    for node := head; node != nil; node = node.Next {
	    fmt.Printf(&quot;%d &quot;, node.Value)
    }
}

Output

E:\go &gt; go run linked_list.go
Please enter a number: 10
Please enter a number: Please enter a number: 20
Please enter a number: Please enter a number: 30
Please enter a number: 10 20 20 30 30 30

答案1

得分: 2

看起来Scanf在处理Windows换行符(\r\n)和Unix换行符(\n)时有所不同。我相信这是Go的旧版本中的一个错误。你正在使用哪个版本?尝试使用1.7或更高版本。

作为一种解决方法,尝试使用fmt.Scanf("%d\n", &value)来显式地读取一个换行符。

英文:

It looks like Scanf is treating windows newlines (\r\n) differently than unix newlines (\n). I believe this was a bug in older versions of Go. What version are you running? Try using 1.7 or later.

As a workaround, try doing fmt.Scanf(&quot;%d\n&quot;, &amp;value) to explicitly eat a newline character.

huangapple
  • 本文由 发表于 2017年3月20日 01:17:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/42889600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定