I need to let a user input multiline text to the console.
Here is my code:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
for {
fmt.Println("How to read all lines here?")
in := bufio.NewReader(os.Stdin)
result, err := in.ReadString('\n')
if err != nil {
fmt.Println(err)
}
fmt.Println("\nresult")
fmt.Println(result)
}
}
I pasted in the console:
Hello
World
It outputs:
How to read all lines here?
Hello
World
result
How to read all lines here?
result
Hello
How to read all lines here?
result
World
How to read all lines here?
result
How to read all lines here?
But I expect it to be:
How to read all lines here?
Hello
World
result
How to read all lines here?
result
Hello
World
How to read all lines here?
I guess I need to use something like EOF instead of '\n'
But how to do it exactly?
Update
peterSo's answer works except in case when I am trying to paste from clipboard a text with one or more empty lines in-between, like:
Hello
World
It prints
Enter Lines:
Hello
WorldResult:
Hello
Enter Lines:
Update 2
The great updated peterSO's answer now works even for text with empty lines.