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:
import (
"bufio"
"os"
)
Scanner
using the bufio.NewScanner
function, passing the os.Stdin
as the input source:scanner := bufio.NewScanner(os.Stdin)
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:
import (
"bufio"
"os"
)
Writer
using the bufio.NewWriter
function, passing os.Stdout
as the output destination:writer := bufio.NewWriter(os.Stdout)
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.