Home > Article > Backend Development > Create a new Scanner using the bufio.NewScanner function
Create a new Scanner using the bufio.NewScanner function
In the Go language, the bufio package provides some convenient tool functions, one of which is the NewScanner function. This function can create a new Scanner object from an io.Reader object for reading input line by line. This article will introduce how to use the bufio.NewScanner function to create a new Scanner object, and provide some sample code to illustrate its use.
First, we need to import the bufio package and the fmt package, because we will use the Scanner object to read the input line by line, and use the fmt package to output the results:
import ( "bufio" "fmt" "os" )
Next, we can Use os.Stdin as the input source to create a new Scanner object, which can read the input line by line through the standard input:
scanner := bufio.NewScanner(os.Stdin)
It is worth noting that the Scanner object is a pointer type, so we need to use: The = operator creates a pointer to a Scanner object.
Now, we can use the Scan method of the Scanner object to read the input one line at a time, and then use the Text method to get the input content. The Scan method will return false when reading to the end of the file or encountering an error. We can use a for loop to continue reading input until the end of the file. The following is a simple sample code:
for scanner.Scan() { line := scanner.Text() fmt.Println("输入内容:", line) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "读取输入失败:", err) os.Exit(1) }
In the above sample code, we use a for loop to continuously read input. After each line of input is read, we use the Text method to obtain the input content. , and output to standard output through the fmt.Println function.
Finally, we use the scanner.Err function to check if an error was encountered while reading the input. If an error occurs, we use the fmt.Fprintln function to output the error message to the standard error stream, and call the os.Exit function to terminate the program. This is a good programming habit that can help us find and solve problems.
To sum up, by using the bufio.NewScanner function, you can easily create a new Scanner object and use it to read the input line by line. I hope this article can help readers quickly get started using the Scanner object and process input more efficiently.
The above is the content of this article. A new Scanner object is created through the bufio.NewScanner function, and corresponding sample code is provided to illustrate its use. I hope readers can get help from it and use this function flexibly in practical applications.
The above is the detailed content of Create a new Scanner using the bufio.NewScanner function. For more information, please follow other related articles on the PHP Chinese website!