How to handle line-based input and output in Go with the io package?

In Go, you can use the bufio package from the standard library along with the io package to handle line-based input and output. Here is an example of how to do it:

Handling Line-based Input:

  1. Import the required packages:
import ( "bufio" "os" )
  1. Create a Scanner using the bufio.NewScanner function, passing the os.Stdin as the input source:
scanner := bufio.NewScanner(os.Stdin)
  1. Iterate through the input using the Scanner.Scan method, which scans for the next line:
for scanner.Scan() { // Access the line of input using scanner.Text() input := scanner.Text() // Process the input // ... }

Handling Line-based Output:

  1. Import the required packages:
import ( "bufio" "os" )
  1. Create a Writer using the bufio.NewWriter function, passing os.Stdout as the output destination:
writer := bufio.NewWriter(os.Stdout)
  1. Write to the output using the Writer.WriteString method and flush the buffer using Writer.Flush:
// Write output line by line writer.WriteString("Output line 1\n") writer.WriteString("Output line 2\n") // ... // Flush the buffer to ensure all data is written writer.Flush()

Note: The Scanner and Writer automatically handle any necessary buffering for you, so there is no need to explicitly manage it.