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

How Can I Read Integer Input from Standard Input in Go?

Susan Sarandon
Release: 2024-12-05 15:35:10
Original
284 people have browsed it

How Can I Read Integer Input from Standard Input in Go?

Getting Integer Input from Standard Input

Reading integer values from standard input is a common requirement in programming. In Go, the fmt.Scanf function provides a convenient way to retrieve numeric input.

Using fmt.Scanf

To use fmt.Scanf, first declare a variable of the desired type (e.g., var i int). Then, call fmt.Scanf with the following syntax:

fmt.Scanf("%d", &i)
Copy after login

Here, "%d" specifies the format specifier for integers. The & character before i is the memory address operator, which allows fmt.Scanf to modify the value of i.

Alternative Methods

If fmt.Scanf is not suitable, other options include:

  1. bufio.Scanner: The bufio.Scanner type provides line-by-line input reading. You can use scanner.Int() to parse an integer from the current line.
  2. strconv.ParseInt: This function takes a string as input and converts it to an integer. You can read the input string using bufio.Scanner or other methods.

Example Usage

The following code demonstrates how to read an integer using fmt.Scanf:

package main

import (
    "fmt"
)

func main() {
    var input int
    fmt.Scanf("%d", &input)
    fmt.Println("Input:", input)
}
Copy after login

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