Home  >  Article  >  Backend Development  >  Read formatted data from input using the fmt.Fscanf function

Read formatted data from input using the fmt.Fscanf function

WBOY
WBOYOriginal
2023-07-24 12:37:09876browse

Use the fmt.Fscanf function to read formatted data from the input

In the Go language, the fmt package provides multiple functions for formatting input and output. Among them, the fmt.Fscanf function can read data from the input in the specified format.

The following is a sample code that demonstrates how to use the fmt.Fscanf function to read formatted data from standard input:

package main

import (
    "fmt"
    "os"
)

func main() {
    var name string
    var age int

    fmt.Print("请输入姓名和年龄(以空格分隔):")
    // 从标准输入中读取格式化的数据
    _, err := fmt.Fscanf(os.Stdin, "%s %d", &name, &age)
    if err != nil {
        fmt.Println("读取数据失败:", err)
        return
    }

    fmt.Println("姓名:", name)
    fmt.Println("年龄:", age)
}

In the above code, two variables name are first declared and age, used to store data read from the input. Then, use the fmt.Print function to print prompt information, prompting the user to enter their name and age. Then, use the fmt.Fscanf function to read data from the standard input, and use the format string "%s %d" to specify the input format, where "%s" means reading a string and "%d" means Read an integer. Note that you need to use the address operator "&" to pass the address of the variable to the fmt.Fscanf function.

If the data is read successfully, the returned result is the number of successfully read parameters and nil error. We use the "_" placeholder in the code to ignore the number of parameters returned and only care about the error. If reading the data fails, a non-nil error is returned.

Finally, use the fmt.Println function to print out the read name and age.

When running the above code, the console will print a prompt message and wait for the user to enter their name and age. After the user completes the input, press the Enter key, and the program will read the entered data and print out the name and age.

To summarize, by using the fmt.Fscanf function to read formatted data from the input, we can easily obtain user input and parse and process it according to the specified format. This gives us greater flexibility and convenience in handling input.

The above is the detailed content of Read formatted data from input using the fmt.Fscanf function. 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