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('\n')
tarr := strings.Split(strings.Trim(text, "\n"), " ")
for i := 0; i < len(tarr); i++ {
num, _ := strconv.ParseInt(tarr[i], 10, 32)
fmt.Println(num)
}
fmt.Println(tarr)
reader.ReadString('\n')
}
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 \n Windows has a line ending of \r\n. This means that the line you've read on Linux is 1 2 3\n while on Windows it is 1 2 3\r\n. If you now remove the \n (i.e. strings.Trim(text, "\n")) and split by space you get 1, 2 and 3 on Linux but you'll get 1, 2, 3\r on Windows.
ParseInt on 3\r 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\r]. Since \r sets the output cursor to the beginning of the current line and does not move to the next line (that's what \n would do) this effectively overrides the initial [ with the final ], resulting on a visible output of ] 1 2 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With