Golang : Scanf function weird error in Windows
Got a newbie to Golang asking for help in the Golang Facebook group and he is having trouble getting his simple codes to work. Apparently this code :
package main
import "fmt"
func main() {
var x [5]string
fmt.Println("Enter your friends name in the list")
for i := 0; i < len(x); i++ {
fmt.Println(i)
fmt.Scanf("%s", &x[i])
fmt.Println(x[i])
}
}
was working fine in *nix based OS. Scanf function was able to capture the user input without trouble. But not the case with Windows ( the Golang version is go1.3.3 windows/386).
It seems that under Windows, Scanf accepted the input twice and thus causing the for loop to end earlier than it suppose too. See picture
To bypass this Scanf "bug" until it was fixed in future version of Golang. Replace Scanf with bufio's ReadString function to capture user input from ... standard input (os.Stdin)
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
var x [5]string
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter your friends name in the list")
for i := 0; i < len(x); i++ {
fmt.Println(i)
x[i], _ = reader.ReadString('\n')
fmt.Println(x[i])
}
}
This replacement codes have been tested on Windows and Linux/MacOSX and confirmed to be working. Hope this tutorial can be useful to you.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+16.5k Golang : Check if a string contains multiple sub-strings in []string?
+14.6k Golang : Send email with attachment(RFC2822) using Gmail API example
+9.1k Golang : Handle sub domain with Gin
+20.9k Golang : Convert PNG transparent background image to JPG or JPEG image
+43.5k Golang : Get hardware information such as disk, memory and CPU usage
+17.2k Golang : Find file size(disk usage) with filepath.Walk
+6.1k Golang : How to write backslash in string?
+13.5k Golang : Count number of runes in string
+7.4k Golang : Individual and total number of words counter example
+19.8k Golang : Archive directory with tar and gzip
+7.3k Golang : How to fix html/template : "somefile" is undefined error?
+7.2k Golang : Null and nil value