Home >Backend Development >Golang >How Can I Read Integers from Standard Input in Go?

How Can I Read Integers from Standard Input in Go?

DDD
DDDOriginal
2024-12-21 01:32:10345browse

How Can I Read Integers from Standard Input in Go?

Reading Integers from Standard Input in Go

Reading an integer from standard input in Go can be achieved effortlessly using fmt.Scanf. However, understanding its usage is essential.

Using fmt.Scanf to Read an Integer

To utilize fmt.Scanf effectively, follow these steps:

  1. Declare an integer variable to store the user input.
  2. In a func main block, utilize fmt.Scanf to take formatted user input. The format string specifies the expected input type. For an integer, it's "%d".
  3. Pass the integer variable as a pointer to fmt.Scanf to capture the input.

An example demonstrating how to read an integer from standard input using fmt.Scanf:

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

Alternative Ways to Read an Integer

While fmt.Scanf is widely used, there are additional methods to read integers from standard input in Go:

  • strconv.Atoi: Converts a string representation of an integer into an integer.
  • bufio.NewReader: Creates a buffered reader to read text from standard input and extract the integer value.

However, fmt.Scanf remains a convenient option for its simplicity and efficiency in reading formatted input.

Conclusion

Reading an integer from standard input in Go can be accomplished using fmt.Scanf or alternative methods as described. Mastering fmt.Scanf is recommended for its versatility and ease of use in various input scenarios.

The above is the detailed content of How Can I Read Integers 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