本文摘自php中文网,作者coldplay.xixi,侵删。
golang处理输入的方法:1、【fmt.Scan】交互式接受输入,通过空格来分词;2、【fmt.Scanln】要指定接收输入的变量名和变量数;3、【 fmt.Scanf】需要指定输入的格式,直接把不需要的部分过滤掉。

golang处理输入的方法:
1. fmt.Scan
fmt.Scan
交互式接受输入,通过空格来分词。调用Scan函数时,要指定接收输入的变量名和变量数。
直到接收完所有指定的变量数,Scan函数才会返回,回车符也无法提前让它返回。
1 2 3 | fmt.Println( "Please enter the firstName and secondName: " )
fmt.Scan(&afirstName, &asecondName)
fmt.Printf( "firstName is %s, secondName is %s\n" , afirstName, asecondName)
|
结果如下:
1 2 3 4 | Please enter the firstName and secondName:
zz
rr
firstName is zz, secondName is rr
|
2. fmt.Scanln
Scanln
调用时,也要指定接收输入的变量名和变量数。
它同Scan的区别,在于 \ n
会让函数提前返回,将返回时还未接收到值的变量赋为空。
1 2 3 | fmt.Println( "Please enter the firstName and secondName: " )
fmt.Scanln(&bfirstName, &bsecondName)
fmt.Printf( "firstName is %s, secondName is %s\n" , bfirstName, bsecondName)
|
结果如下:
1 2 3 | Please enter the firstName and secondName:
zr
firstName is zr, secondName is
|
3. fmt.Scanf
用Scanf
处理输入,是比较灵活的一种处理方式。
需要指定输入的格式,适用于完全了解输入格式的场景,可以直接把不需要的部分过滤掉。
1 2 3 | fmt.Println( "Please enter the firstName and secondName: " )
fmt.Scanf( "//%s\n%s" , &cfirstName, &csecondName)
fmt.Printf( "firstName is %s, secondName is %s" , cfirstName, csecondName)
|
结果如下:
1)这个场景,在接收输入时,就把不需要的部分“//” 和 “\n”过滤掉了,接收到是有用的两个字符串zz和rr。
1 2 3 4 | Please enter the firstName and secondName:
rr
firstName is zz, secondName is rr
|
2)如果输入不符合指定的格式,从不符合处开始,其后的变量值都为空。
1 2 3 | Please enter the firstName and secondName:
firstName is zr, secondName is
|
相关学习推荐:Go语言教程
以上就是golang如何处理输入?的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
golang如何捕获错误
手撸golang 基本数据结构与算法 队列
golang浮点数精度丢失问题扩展包怎么解决
go语言的依赖管理
详解go 语言中的方法
golang和erlang区别
golang xorm mysql代码生成器
go好用的类型转换第三方组件
深度剖析golang sync.once源码
golang和nodejs的区别是什么?
更多相关阅读请进入《golang》频道 >>
老貘
一个与时俱进的Go编程知识库。
转载请注明出处:木庄网络博客 » golang如何处理输入?