GoLang fmt.Scan类型错误跳过下一个fmt.Scan。

huangapple go评论64阅读模式
英文:

GoLang fmt.Scan type error skip next fmt.Scan

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是GoLang的初学者,这是一个来自教程的示例代码。

func main() {
	for {
		var name string
		var email string
		var userTickets uint
		// 询问用户信息
		fmt.Println("请输入您的姓名")
		fmt.Scan(&name)

		fmt.Println("请输入您的电子邮件")
		fmt.Scan(&email)

		// 询问用户票数
		fmt.Println("请输入票数")
		if _, err := fmt.Scanln(&userTickets); err != nil {
			fmt.Println(err)
		}
	}
}

我发现了一个有趣的问题:
如果我在"请输入票数"中输入"-1",它会抛出一个错误,因为userTickets的类型是uint。由于这个错误,它还会在下一次循环中为"请输入您的姓名"添加一个换行符。
结果会像这样:

请输入您的姓名
Test
请输入您的电子邮件
Test
请输入票数
-1
expected integer
请输入您的姓名 <= 这个输入被跳过了
请输入您的电子邮件

所以我想知道为什么会发生这种情况?如何解决这个问题(不改变uint类型为int类型)?

英文:

Am a beginner of GoLang here is a sample code from a tutorial.

func main() {
	for {
		var name string
		var email string
		var userTickets uint
		// ask user for info
		fmt.Println(&quot;Input your Name please&quot;)
		fmt.Scan(&amp;name)

		fmt.Println(&quot;Input your Email please&quot;)
		fmt.Scan(&amp;email)

		// ask user for number of tickets
		fmt.Println(&quot;Input number of ticket&quot;)
		if _, err := fmt.Scanln(&amp;userTickets); err != nil {
			fmt.Println(err)
		}
	}
}

Here is an interesting thing I found:
if I entered "-1" in "Input number of ticket". It will throw an error since userTickets is uint. With that err it will also put an "enter/next line" for "Input your Name please" in the next loop.
The result would look like this

Input your Name please
Test
Input your Email please
Test
Input number of tickect
-1
expected integer
Input your Name please &lt;= this input is skipped
Input your Email please

So just wondering why this heppened? How can I resolve that (without changing type from uint to int)?

答案1

得分: 4

只是想知道为什么会发生这种情况?

因为-1不能存储在uint类型中。

我如何解决这个问题(不改变uint类型为int类型)?

你无法解决这个问题。

(正确的做法是不使用fmt.Scan,而是始终将整行读入字符串,然后解析字符串。)

英文:

> So just wondering why this heppened?

Because -1 cannot be stored in an uint.

> How can I resolve that (without changing type from uint to int)?

You cannot.

(The right thing to do is not to use fmt.Scan but to always read whole lines into a string and parse the string.)

huangapple
  • 本文由 发表于 2022年3月2日 20:03:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/71322375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定