Golang程序在电脑上输出异常内容怎么办

Golang程序在电脑上输出异常内容怎么办 当我在在线Go编译器中执行以下代码时,它按预期工作,但在我电脑上(Golang 1.17.5)执行此代码时,会打印出奇怪的输出。

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)

	}

}

//检查输入的字符串是否在countries字符串数组中

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终端输出:

go run main.go
country code : dd
country code : 

我的终端输出:

go run main.go
country code : dd
country code : country code :

更多关于Golang程序在电脑上输出异常内容怎么办的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

虽然没有直接回答你的问题,但

the_oddsaint:

for 1 == 1 {

更符合惯用写法的形式是:

for {

关于你实际的问题,可能是 CRLF 行结束符导致了两次 Scanf 失败。我建议先读取整行输入,然后再从中解析。

还有一点,不要忽略 Scanf 返回的 error

更多关于Golang程序在电脑上输出异常内容怎么办的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


问题在于fmt.Scanf的缓冲处理。当你在本地环境中输入"dd"后按回车,实际上输入的是"dd\n"。fmt.Scanf("%s", &country)只读取了"dd",而换行符\n留在了输入缓冲区中,导致后续的fmt.Scanf立即读取到这个换行符并返回。

以下是修复后的代码:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

var (
	countries = []string{"au", "in", "jp", "kr", "tr"}
	country   string
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	
	if len(os.Args) < 2 {
		fmt.Printf("country code : ")
		country, _ = reader.ReadString('\n')
		country = strings.TrimSpace(country)
		checkcountry(&country, reader)
	} else {
		checkcountry(&country, reader)
	}
}

func checkcountry(country *string, reader *bufio.Reader) {
	for {
		if is_string_in_array(*country, countries) {
			fmt.Printf("country : %s, breaking\n", *country)
			break
		} else {
			fmt.Printf("country code : ")
			input, _ := reader.ReadString('\n')
			*country = strings.TrimSpace(input)
		}
	}
}

func is_string_in_array(str string, array []string) bool {
	for _, i := range array {
		if str == i {
			return true
		}
	}
	return false
}

或者使用fmt.Scanln替代fmt.Scanf

func checkcountry(country *string) {
	for {
		if is_string_in_array(*country, countries) {
			fmt.Printf("country : %s, breaking\n", *country)
			break
		} else {
			fmt.Printf("country code : ")
			fmt.Scanln(country)
		}
	}
}

主要修改:

  1. 使用bufio.NewReader读取整行输入,包括换行符
  2. 使用strings.TrimSpace去除输入中的空白字符和换行符
  3. 或者使用fmt.Scanln替代fmt.Scanf,它会自动处理换行符

在线编译器可能对标准输入的处理方式不同,所以没有出现这个问题。

回到顶部