读取用户的输入数据
我们怎样读取用户从键盘(控制台)输入的数据?输入指从键盘或其它标准输入(os.Stdin)读取数据。最简单的方法是使用fmt包里的Scan-或Sscan-系列函数,下面用个例子说明一下:
package main
import "fmt"
func main() {
var name, school, str, sex string
var height float64
str = "1.81 man"
fmt.Scanln(&name)
fmt.Println("your name is: ", name)
fmt.Scanf("%s", &school)
fmt.Printf("your school is : %s\n", school)
fmt.Sscanf(str, "%f %s", &height, &sex)
fmt.Println("your height is : ", height, "m", ", and you are a ", sex)
}
程序运行:
siskinc
your name is: siskinc
suse
your school is : suse
your height is : 1.81 m , and you are a man
Process finished with exit code 0
另外,我们也可以使用 bufio包里带缓冲的Reader,例如:
package main
import (
"bufio"
"os"
"fmt"
)
func main() {
inputReader := bufio.NewReader(os.Stdin)
fmt.Println("Please input your name:")
input, err := inputReader.ReadString('\n')
if err != nil {
fmt.Printf("Found an error: %s\n", err)
} else {
input = input[:len(input)-1]
fmt.Printf("Hello, %s\n", input)
}
}
程序运行:
package main
import (
"bufio"
"os"
"fmt"
)
func main() {
inputReader := bufio.NewReader(os.Stdin)
fmt.Println("Please input your name:")
input, err := inputReader.ReadString('\n')
if err != nil {
fmt.Printf("Found an error: %s\n", err)
} else {
input = input[:len(input)-1]
fmt.Printf("Hello, %s\n", input)
}
}
网友评论