用户输入的数字在Go代码中没有被转换或解释为整数。

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

The number entered by the user is not being converted or interpreted as an integer in Go code

问题

我正在使用Visual Studio Code运行这段代码。

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() {
	min, max := 1, 100
	rand.Seed(time.Now().UnixNano())
	secretNumber := rand.Intn(max-min) + min
	fmt.Println(secretNumber)

	fmt.Println("猜一个1到100之间的数字")
	fmt.Println("请输入你的猜测")

	reader := bufio.NewReader(os.Stdin)
	input, err := reader.ReadString('\n')
	if err != nil {
		fmt.Println("读取输入时发生错误,请重试", err)
		return
	}

	input = strings.TrimSuffix(input, "\n")

	guess, err := strconv.Atoi(input)
	if err != nil {
		fmt.Println("无效的输入,请输入一个整数值")
		return
	}

	fmt.Println("你的猜测是", guess)
}

我从这个链接https://freshman.tech/golang-guess/复制了这段代码。当我在我的系统上运行这段代码时,在按下回车键输入数字后,代码生成了以下输出。

56
猜一个1到100之间的数字
请输入你的猜测
63
无效的输入,请输入一个整数值

有人可以指导我如何解决这个问题吗?

英文:

I am running this code in Visual studio code.

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() {
	min, max := 1, 100
	rand.Seed(time.Now().UnixNano())
	secretNumber := rand.Intn(max-min) + min
	fmt.Println(secretNumber)

	fmt.Println("Guess a number between 1 and 100")
	fmt.Println("Please input your guess")

	reader := bufio.NewReader(os.Stdin)
	input, err := reader.ReadString('\n')
	if err != nil {
		fmt.Println("An error occured while reading input. Please try again", err)
		return
	}

	input = strings.TrimSuffix(input, "\n")

	guess, err := strconv.Atoi(input)
	if err != nil {
		fmt.Println("Invalid input. Please enter an integer value")
		return
	}

	fmt.Println("Your guess is", guess)
}

I have copied this code from this link https://freshman.tech/golang-guess/ When I run this code on my system, after entering the number by hitting the enter key instead of printing the entered number my code is generating this output.

56
Guess a number between 1 and 100
Please input your guess
63
Invalid input. Please enter an integer value

Can anyone please guide me how to solve this problem.

答案1

得分: 1

你是在Windows上吗?我怀疑你的控制台在每行末尾给出的是\r\n,而不仅仅是\n

你可以从字符串中删除所有空白字符...

不要使用这个:

input = strings.TrimSuffix(input, "\n")

而要使用这个:

input = strings.TrimSpace(input)

这将从字符串的开头和结尾删除空格,包括\r\n

英文:

Are you on Windows? I suspect your console is giving you \r\n at the end of each line, not just \n.

You can trim all whitespace from a string...

Instead of this:

input = strings.TrimSuffix(input, "\n")

Use this:

input = strings.TrimSpace(input)

This will trim space, including \r and \n, from both the beginning and end.

huangapple
  • 本文由 发表于 2022年1月26日 13:07:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/70858871.html
匿名

发表评论

匿名网友

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

确定