douqianzha6213 2019-06-08 20:44
浏览 55
已采纳

Golang程序在Windows 10中给出了不正确的结果

First of all, I am a newbie to Go programming. I have a simple Golang program which is giving the correct output in Linux environment but not in my Windows 10 PC.

The code is as follows:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('
')
    tarr := strings.Split(strings.Trim(text, "
"), " ")

    for i := 0; i < len(tarr); i++ {
        num, _ := strconv.ParseInt(tarr[i], 10, 32)
        fmt.Println(num)
    }

    fmt.Println(tarr)
    reader.ReadString('
')
}

If I enter 1 2 3 as input from the terminal, I am getting the following output in Windows 10 (go version go1.12.5 windows/amd64):

1
2
0
]1 2 3

I am getting the following output in Linux Elementary OS (go version go1.12.5 linux/amd64)

1
2
3
[1 2 3]

Can anyone explain why this is happening?

  • 写回答

1条回答 默认 最新

  • doujiyun8846 2019-06-08 21:01
    关注

    While UNIX (and Linux) have a line ending of Windows has a line ending of . This means that the line you've read on Linux is 1 2 3 while on Windows it is 1 2 3 . If you now remove the (i.e. strings.Trim(text, " ")) and split by space you get 1, 2 and 3 on Linux but you'll get 1, 2, 3 on Windows.

    ParseInt on 3 returns 0 and likely returns an error - which you explicitly ignore. That's why you get the output of 1, 2 and 0 on Windows. Also, the array on Windows will be printed as [1 2 3]. Since sets the output cursor to the beginning of the current line and does not move to the next line (that's what would do) this effectively overrides the initial [ with the final ], resulting on a visible output of ] 1 2 3.

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭