Printing weird output in my computer

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 :

Not answering your question, but

is more idiomatically written as
for {

Regarding your actual questing, perhaps CRLF line terminator results in two failed Scanfs. I’d read the entire input line first, and then parse from it.

One more thing, don’t ignore the error returned from Scanf.

1 Like