如何在golang中处理输入

发布时间:2020-07-20 14:35:59 作者:Leah
来源:亿速云 阅读:291

这期内容当中小编将会给大家带来有关如何在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 %s\n", afirstName, asecondName)

结果如下:

Please enter the firstName and secondName:
zz
rr
firstName 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 %s\n", bfirstName, bsecondName)

结果如下:

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

3. fmt.Scanf

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

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

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。

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

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

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


上述就是小编为大家分享的如何在golang中处理输入了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 我在Payground里面输入代码的时候没有直接,这个需要如
  2. Golang获取终端输入

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

golang olang ola

上一篇:如何解决php上传中文文件文件名乱码的问题

下一篇:解决python无法调用cv2的问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》