M
M
marselabdullin2020-06-24 17:12:15
go
marselabdullin, 2020-06-24 17:12:15

Why does it give an error that it is not the number go that is entered?

I created the simplest program for working out the basic syntax in go according to the tutorial, but the compiler swears that I did not enter a number, although I only enter numbers

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("Guess a number between 1 and 100")
  fmt.Println("Please input your guess")

  attempts := 0
  for {
    attempts++
    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)
      continue
    }

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

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

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

    if guess > secretNumber {
      fmt.Println("Your guess is bigger than the secret number. Try again")
    } else if guess < secretNumber {
      fmt.Println("Your guess is smaller than the secret number. Try again")
    } else {
      fmt.Println("Correct, you Legend! You guessed right after", attempts, "attempts")
      break
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
12rbah, 2020-06-24
@12rbah

invalid input. Please enter an integer value strconv.Atoi: parsing "2\r": invalid syntax - throws this error if err is output, so you can remove one more character strings.TrimSuffix(input, "\r")and it will work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question