golang处理输入
April_Luv_Choco · · 2584 次点击 · · 开始浏览golang对于输入的处理,在我看来是非常方便的。今年的秋招笔试,果断弃c++了。
首先来讲一下几种简单的输入处理。
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
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
golang对于输入的处理,在我看来是非常方便的。今年的秋招笔试,果断弃c++了。
首先来讲一下几种简单的输入处理。
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