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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 16:37:18862browse

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

Reading Integer Input from Standard Input in Go

Acquiring an integer input from standard input in Go involves using the fmt.Scanf function. This function takes a format specifier and a pointer to a variable where the input is stored. For integers, the format specifier is %d. The code sample below demonstrates its usage:

func main() {
    var i int
    n, err := fmt.Scanf("%d", &i)
    if err != nil {
        // Handle error or panic as necessary
    }
    if n != 1 {
        // Handle error if the number of input values is not 1
    }
}

In addition to fmt.Scanf, there are other ways to read an integer from standard input. One alternative is to use the bufio package's Scanner type. Here's an example:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Print("Enter an integer: ")
    scanner.Scan()
    input := scanner.Text()
    i, err := strconv.Atoi(input)
    if err != nil {
        // Handle error or panic as necessary
    }
    fmt.Printf("You entered: %d\n", i)
}

Both methods have their advantages and disadvantages. However, using fmt.Scanf is generally simpler and more convenient.

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