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?
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
.