Home  >  Article  >  Backend Development  >  How to use the scan method to implement console input

How to use the scan method to implement console input

PHPz
PHPzOriginal
2023-04-11 09:13:34911browse

In the Go language, you can use the scan method to read data from the standard input. The scan method can read any type of data, including strings, numbers, Boolean values, etc. This article will introduce in detail how to use the scan method to implement console input.

Basic syntax

The basic syntax of the scan method is as follows:

func Scan(a ...interface{}) (n int, err error)

Read data from the input and store it into the specified parameters . Parameter a represents the data that needs to be read. Any number of parameters can be passed. Each parameter is a pointer type used to store the input data. The return value n indicates the number of successfully read parameters, and the return value err indicates possible errors.

The following is a simple example that demonstrates how to read two integers from the console:

func main() {
    var a, b int
    fmt.Print("请输入两个整数:")
    n, err := fmt.Scan(&a, &b)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("成功读取了 %d 个参数:%v\n", n, []int{a, b})
}

Through the above code, we can see the basics of the Scan method usage. Executing the above code, the program will prompt the user to enter two integers. After the user input is completed, the program will store the two integers into the variables a and b, and output the two integers. .

Characteristics of scan

Scan method has the following characteristics:

1. Ignore spaces

ScanWhen reading data, the method will automatically ignore the spaces between the data. As shown in the following code:

func main() {
    var a, b, c string
    fmt.Print("请输入三个字符串:")
    n, err := fmt.Scan(&a, &b, &c)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("成功读取了 %d 个参数:%v\n", n, []string{a, b, c})
}

Input the string hello world go, the program will automatically ignore the spaces between the strings and output these three strings.

2. Waiting for carriage return

Scan method will wait for the user to enter the carriage return character \n when reading data, indicating that the input is completed . If the user does not enter a carriage return character, the program will wait for user input. As shown in the following code:

func main() {
    var s string
    fmt.Print("请输入一个字符串:")
    n, err := fmt.Scan(&s)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("成功读取了 %d 个参数:%v\n", n, s)
}

After inputting the string hello, the program will not output the result immediately, but waits for the user to enter the carriage return character \n , the result will be output.

3. Newline characters will not be read

Scan method will not read newline characters in the input when reading data\n. For example, when we read a string through the Scan method, the newline characters \n in the input string will not be read. As shown in the following code:

func main() {
    var s string
    fmt.Print("请输入一个字符串:")
    n, err := fmt.Scan(&s)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("成功读取了 %d 个参数:%v\n", n, s)
}

Input the string hello\nworld, the program will only read the string hello, not the string Newline character \n in .

In-depth analysis

The implementation of the Scan method is based on the Scanf function of the fmt package. The Scanf method has the following features:

1. Formatted input

Scanf method supports formatted input. You can specify the data type to be read through a format string. For example, we can read an integer and a string through the following format string:

func main() {
    var a int
    var b string
    fmt.Print("请输入一个整数和一个字符串:")
    n, err := fmt.Scanf("%d %s", &a, &b)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("成功读取了 %d 个参数:%v\n", n, []interface{}{a, b})
}

In the above code, the defined format string "%d %s" means First read an integer, then read a string, separated by spaces.

2. Custom delimiter

Scanf method supports custom delimiter. By default, the Scanf method uses spaces as delimiters. The delimiter can be customized through the ScanState parameter of the Scanf method. As shown in the following code:

func main() {
    var a, b string
    fmt.Print("请输入两个字符串,用逗号分隔:")
    s := bufio.NewScanner(os.Stdin)
    s.Split(func(data []byte, atEOF bool) (adv int, token []byte, err error) {
        for i := 0; i < len(data); i++ {
            if data[i] == ',' {
                return i + 1, data[:i], nil
            }
        }
        return 0, data, bufio.ErrFinalToken
    })
    if s.Scan() {
        a = s.Text()
    }
    if s.Scan() {
        b = s.Text()
    }
    fmt.Printf("您输入的字符串是:%v\n", []string{a, b})
}

In the above code, we create a Scanner object through the NewScanner method of the bufio package, and The separator is customized through the Split method. In the delimiter function, we use comma as delimiter to parse the input string and store it into variables a and b.

Summary

Through the introduction of this article, we have learned about the basic syntax and characteristics of the Scan method and how to implement console input. It should be noted that the Scan method will not read the newline character \n into the input when processing the input. In addition, the Scanf method supports custom delimiters and formatted input, which can handle console input more flexibly.

The above is the detailed content of How to use the scan method to implement console input. 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