栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

golang如何处理输入?

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

golang如何处理输入?

golang处理输入的方法:1、【fmt.Scan】交互式接受输入,通过空格来分词;2、【fmt.Scanln】要指定接收输入的变量名和变量数;3、【 fmt.Scanf】需要指定输入的格式,直接把不需要的部分过滤掉。

golang处理输入的方法:

1. fmt.Scan

fmt.Scan交互式接受输入,通过空格来分词。调用Scan函数时,要指定接收输入的变量名和变量数。

直到接收完所有指定的变量数,Scan函数才会返回,回车符也无法提前让它返回。

fmt.Println("Please enter the firstName and secondName: ")fmt.Scan(&afirstName, &asecondName)fmt.Printf("firstName is %s, secondName is %sn", afirstName, asecondName)

结果如下:

Please enter the firstName and secondName:zzrrfirstName is zz, secondName is rr

2. fmt.Scanln

Scanln调用时,也要指定接收输入的变量名和变量数。

它同Scan的区别,在于 n 会让函数提前返回,将返回时还未接收到值的变量赋为空。

fmt.Println("Please enter the firstName and secondName: ")fmt.Scanln(&bfirstName, &bsecondName)fmt.Printf("firstName is %s, secondName is %sn", bfirstName, bsecondName)

结果如下:

Please enter the firstName and secondName:zrfirstName is zr, secondName is

3. fmt.Scanf

用Scanf处理输入,是比较灵活的一种处理方式。

需要指定输入的格式,适用于完全了解输入格式的场景,可以直接把不需要的部分过滤掉。

fmt.Println("Please enter the firstName and secondName: ")fmt.Scanf("//%sn%s", &cfirstName, &csecondName)fmt.Printf("firstName is %s, secondName is %s", cfirstName, csecondName)

结果如下:

1)这个场景,在接收输入时,就把不需要的部分“//” 和 “n”过滤掉了,接收到是有用的两个字符串zz和rr。

Please enter the firstName and secondName://zzrrfirstName is zz, secondName is rr

2)如果输入不符合指定的格式,从不符合处开始,其后的变量值都为空。

Please enter the firstName and secondName://zr uifirstName is zr, secondName is

相关学习推荐:Go语言教程

以上就是golang如何处理输入?的详细内容,更多请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/793993.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号