Variants:
Scan
,Scanln
,Scanf
,Sscanf
In Go language, to read data from standard input (keyboard by default), you can use the Scan and Scanln functions in the fmt package.
-
Scan()
: Note that&num
if the input data format is incorrect, an error will be returned.var num int fmt.Scan(&num)
-
Scanln()
: Similar to Scan, but only reads one line of data (treats a newline as a termination)var name string fmt.Scanln(&name)
-
Scanf()
: Parse the input according to the specified format. The example program reads an integer and a string from standard input and stores them in the variables num and name respectively:var num int var name string fmt.Scanf("%d %s", &num, &name)
-
Sscanf()
: String scan, read data from a string. Sscanf works like Scanf, except it reads from a string instead of standard input.var num int var name string fmt.Sscanf("10 foo", "%d %s", &num, &name)
Note : Do not confuse the usage of various input methods
fmt.Scan("%d", &num) // 错误的写法
fmt.Scan(&num) // 正确
The first kind of error, which uses to Scan
get input, but uses Scanf
the wording of .