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: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 %s\n", 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("//%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://zzrrfirstname is zz, secondname is rr
2)如果输入不符合指定的格式,从不符合处开始,其后的变量值都为空。
please enter the firstname and secondname://zr uifirstname is zr, secondname is
相关学习推荐:go语言教程
以上就是golang如何处理输入?的详细内容。
