go student mgr 增删改查管理 fmt.Scanf运用
package main
import (
"fmt"
"os"
//"MyProject/pingguoxueyuan/gostudy/listen13/homework/student_mgr"
)
// 把下面这个结构体和函数注释了就不能单独go run 运行了,要go build才能把2个文件编译到一起
type Student struct{
Username string
Sex int
Score float32
Grade string
}
func NewStudent(username string, sex int, score float32,grade string) (stu *Student){
stu = &Student{
Username :username,
Sex:sex,
Score:score,
Grade:grade,
}
return
}
var (
AllStudents []*Student
)
func showMenu() {
fmt.Println("请输入对应的选项号")
fmt.Println("1. add student")
fmt.Println("2. modify student")
fmt.Println("3. ashow all student")
fmt.Println("4. exited\n")
}
func inputStudent() *Student {
var (
username string
sex int
grade string
score float32
)
fmt.Println("Please input username")
fmt.Scanf("%s \r\n",&username)
fmt.Println("Please input sex:[0|1]")
fmt.Scanf("%d \r\n",&sex)
fmt.Println("Please input grade:[0-6]")
fmt.Scanf("%s \r\n",&grade)
fmt.Println("Please input score:[0-100]")
fmt.Scanf("%f \r\n",&score)
stu := NewStudent(username,sex,score,grade)
return stu
}
func AddStudent() {
stu := inputStudent()
for index,v := range AllStudents {
fmt.Printf("v.Username == stu.Username is %t\n",v.Username == stu.Username)
if v.Username == stu.Username{
fmt.Printf("v.Username =%s,index=%d\n",v.Username,index)
AllStudents[index] = stu
return
}
}
AllStudents = append(AllStudents,stu)
fmt.Printf("user %s success inserted\n",stu.Username)
}
func ModifyStudent() {
stu := inputStudent()
for index,v := range AllStudents{
if v.Username == stu.Username{
AllStudents[index] = stu
return
}
}
fmt.Printf("user %s is not fouond\n", stu.Username)
}
func ShowAllStudent() {
for _,v :=range AllStudents{
fmt.Printf("user:%s info %#v\n",v.Username,v)
}
}
func main() {
for {
showMenu()
var sel int
fmt.Scanf("%d\n",&sel) // Scanf 一定要有换行符,否则会把下次的输入的enter换行符读出来
switch sel{
case 1:
AddStudent()
case 2:
ModifyStudent()
case 3:
ShowAllStudent()
case 4:
os.Exit(0)
}
}
}
写入自己的博客中才能记得长久