我想从命令行读取标准输入,但在提示输入之前,我的尝试已经以程序退出而告终。我正在寻找c#中的Console.ReadLine()的等效。
这是我目前拥有的:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println(text)
fmt.Println("Enter text: ")
text2 := ""
fmt.Scanln(text2)
fmt.Println(text2)
ln := ""
fmt.Sscanln("%v", ln)
fmt.Println(ln)
}
清楚地读入两个提示值:
// Create a single reader which can be called multiple times
reader := bufio.NewReader(os.Stdin)
// Prompt and read
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Print("Enter More text: ")
text2, _ := reader.ReadString('\n')
// Trim whitespace and print
fmt.Printf("Text1: \"%s\", Text2: \"%s\"\n",
strings.TrimSpace(text), strings.TrimSpace(text2))
下面是一段:
Enter text: Jim
Enter More text: Susie
Text1: "Jim", Text2: "Susie"
清楚地读入两个提示值:
// Create a single reader which can be called multiple times
reader := bufio.NewReader(os.Stdin)
// Prompt and read
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Print("Enter More text: ")
text2, _ := reader.ReadString('\n')
// Trim whitespace and print
fmt.Printf("Text1: \"%s\", Text2: \"%s\"\n",
strings.TrimSpace(text), strings.TrimSpace(text2))
下面是一段:
Enter text: Jim
Enter More text: Susie
Text1: "Jim", Text2: "Susie"
另一种方法是在循环中读取多个输入,它可以处理带有空格的输入:
package main
import (
"fmt"
"bufio"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
var text string
for text != "q" { // break the loop if text == "q"
fmt.Print("Enter your text: ")
scanner.Scan()
text = scanner.Text()
if text != "q" {
fmt.Println("Your text was: ", text)
}
}
}
输出:
Enter your text: Hello world!
Your text was: Hello world!
Enter your text: Go is awesome!
Your text was: Go is awesome!
Enter your text: q