When I execute below code in Online Go compiler it works as expected, but when I execute this code in my computer(Golang 1.17.5). It prints weird output.
package main
import (
"fmt"
"os"
)
//variables
var (
countries = []string{"au", "in", "jp", "kr", "tr"}
country string
)
//main function
func main() {
if len(os.Args) < 2 {
fmt.Printf("country code : ")
fmt.Scanf("%s", &country)
checkcountry(&country)
// log.Printf("")
} else {
checkcountry(&country)
}
}
//check whether the entered string is in countries string_array
func checkcountry(country *string) {
for 1 == 1 {
if is_string_in_array(*country, countries) {
fmt.Printf("country : %s, breaking\n", *country)
break
} else {
fmt.Printf("country code : ")
fmt.Scanf("%s", country)
}
}
}
func is_string_in_array(str string, array []string) bool {
for _, i := range array {
if str == i {
return true
}
}
return false
}
repl.it terminal output :
go run main.go
country code : dd
country code :
my terminal output :
go run main.go
country code : dd
country code : country code :
CodePudding user response:
Instead of fmt.Scanf you can use bufio package to read input as shown in below example which parse input till newline.
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println(text)
CodePudding user response:
Rather than using fmt.Scanf you should probably use bufio.Scanner which is a little smarter in detecting newlines and whitespace.
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Country code:")
scanner.Scan()
text := scanner.Text()
fmt.Println(text)
}
