Home >Backend Development >Golang >How to Read an Integer from Standard Input in Go?

How to Read an Integer from Standard Input in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 12:31:12305browse

How to Read an Integer from Standard Input in Go?

Reading an Integer from Standard Input in Go

Question:

How can you utilize the fmt.Scanf function to retrieve an integer input from the standard input in Go? If this feature is not supported by fmt.Scanf, provide an alternative method for effectively reading a single integer.

Answer:

The official Go documentation provides comprehensive information on the fmt.Scanf function, located at http://golang.org/pkg/fmt/#Scanf. The fmt.Scanf function allows you to read formatted input from the standard input. In this case, you can use the fmt.Scanf function to read an integer by providing a format string %d. The syntax for reading an integer using fmt.Scanf is:

_, err := fmt.Scanf("%d", &variable_to_store_input)

Here's an example of reading an integer using fmt.Scanf:

func main() {
    var i int
    _, err := fmt.Scanf("%d", &i)
}

If you prefer an alternative method for reading a single integer, you can use the following approach:

  1. Import the bufio package:

    import "bufio"
  2. Create a bufio.Scanner instance:

    scanner := bufio.NewScanner(os.Stdin)
  3. Read the input using the Next() method:

    scanner.Scan()
  4. Retrieve the input as an integer using the Int() method:

    input, _ := strconv.Atoi(scanner.Text())

This method allows you to read a single integer from the standard input using the bufio package.

The above is the detailed content of How to Read an Integer from Standard Input in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn