go语言的标准输入-scan 和bufio
package main
import "fmt"
var (
firstName, lastName, s string
i int
f float32
input = "56.12 / 5212 / Go"
format = "%f / %d / %s"
)
func main() {
fmt.Println("Please input your full name: ")
fmt.Scanln(&firstName, &lastName)
// fmt.Scanf(“%s %s”, &firstName, &lastName)
fmt.Printf("Hi %s %s!\n", firstName, lastName)
fmt.Sscanf(input, format, &f, &i, &s)
fmt.Println("From the string we read: ", f, i, s)
}
package main
import (
"bufio"
"fmt"
"os"
)
var inputReader *bufio.Reader
var input string
var err error
func main() {
inputReader = bufio.NewReader(os.Stdin)
fmt.Println("Please enter some input: ")
input, err = inputReader.ReadString('S') //func (b *Reader) ReadString(delim byte) (line string, err error) ,‘S’ 这个例子里使用S表示结束符,也可以用其它,如'\n'
if err == nil {
fmt.Printf("The input was: %s\n", input)
}
}
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
inputReader := bufio.NewReader(os.Stdin)
fmt.Println("please input your name:")
input, err := inputReader.ReadString('\n')
if err != nil {
fmt.Println("There ware errors reading,exiting program.")
return
}
fmt.Printf("Your name is %s", input)
//对unix:使用“\n”作为定界符,而window使用"\r\n"为定界符
//Version1
/*
switch input {
case "Philip\r\n":
fmt.Println("Welcome Philip!")
case "Chris\r\n":
fmt.Println("Welcome Chris!")
case "Ivo\r\n":
fmt.Println("Welcome Ivo!")
default:
fmt.Println("You are not welcome here! Goodbye!")
}
*/
//version2
/*
switch input {
case "Philip\r\n":
fallthrough
case "Ivo\r\n":
fallthrough
case "Chris\r\n":
fmt.Printf("Welcome %s\n", input)
default:
fmt.Printf("You are not welcome here! Goodbye!")
}
*/
//version3
switch input {
case "Philip\r\n", "Ivo\r\n", "Chris\r\n":
fmt.Printf("Welcome %s\n", input)
default:
fmt.Println("You are not welcome here! Goodbye!")
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。