Go core development study notes (eight) - Scanf user interaction input

Keyboard input sentence InputDemo.go
similar PY in input ()

  1. Import package fmt
  2. Call fmt package fmt.Scanf () or fmt.Scanln () function can be done two input

fmt.Scanf () and fmt.Scanln () the difference:

  1. Contrast C language may know, incoming values ​​and behavior is no different from the C language scanf, and package main, import "fmt" is similar to #include <stdio.h>, learning by analogy
  2. ScanX () parameter is passed the address of a variable, i.e. & <variable>
  3. Scanln () function can only transfer a single value, but Scanf () while passing a plurality of values ​​may be formatted

Example: Enter the four values ​​:( player name, age, salary, whether to enter the NBA), print it out

Use Scanln () output:

package main
import "fmt"
func main() {
//首先定义四个变量
var(
	name string
	age byte
	salary float64
	isNba_reg bool
)
/*
为几个变量赋值,使用fmt.Scanln()函数
*/
	fmt.Println("请输入球员姓名:")
	fmt.Scanln(&name)                           //传递的是变量地址,Scanln()内部接受地址,最后使用*&name完成对name内存中值的赋予(改变)
	fmt.Println("请输入球员年龄:")
	fmt.Scanln(&age)
	fmt.Println("请输入球员薪资(million):")
	fmt.Scanln(&salary)
	fmt.Println("请输入球员是否为NBA正式球员:")
	fmt.Scanln(&isNba_reg)
	
	fmt.Println("输入结果检视:\n")
	fmt.Printf("球员名称:%v\n",name)
	fmt.Printf("球员年龄:%v\n",age)
	fmt.Printf("球员薪资:%v\n",salary)
	fmt.Printf("是否为NBA正式球员:%v\n",isNba_reg)
}

Use Scanf () output:

package main
import "fmt"
func main() {
//首先定义四个变量
var (
    name      string
    age       byte
    salary    float64
    isNba_reg bool
)
	/*
	为几个变量赋值,使用fmt.Scanln()函数
    */
    fmt.Println("请输入球员姓名,球员年龄,球员薪水,球员是否为正式球员四项内容" +
    "(使用空格来间隔): ")
    fmt.Scanf("%s %d %f %t", &name, &age, &salary, &isNba_reg)
    fmt.Println("\n")
    fmt.Println("输入结果检视:")
    fmt.Printf("球员名称:%v\n", name)
    fmt.Printf("球员年龄:%v\n", age)
    fmt.Printf("球员薪资:%v\n", salary)
    fmt.Printf("是否为NBA正式球员:%v\n", isNba_reg)
}
Published 50 original articles · won praise 18 · views 4021

Guess you like

Origin blog.csdn.net/weixin_41047549/article/details/89605436