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
Release: 2024-12-06 12:31:12
Original
335 people have browsed it

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)
Copy after login

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

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

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

  1. Import the bufio package:

    import "bufio"
    Copy after login
  2. Create a bufio.Scanner instance:

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

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template