我需要让用户向控制台输入多行文本。
这是我的代码:
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)
}
}
我粘贴在控制台中:
Hello
World
它输出:
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?
但我希望它是:
How to read all lines here?
Hello
World
result
How to read all lines here?
result
Hello
World
How to read all lines here?
我想我需要使用类似的东西EOF而不是'\n' But 怎么做呢?
更新
peterSo 的答案有效,除非我尝试从剪贴板粘贴文本,中间有一个或多个空行,例如:
Hello
World
它打印
Enter Lines:
Hello
WorldResult:
Hello
Enter Lines:
更新 2
伟大的更新 peterSO 的答案现在甚至适用于带有空行的文本。
jeck猫
相关分类