菜鸟求教,一个简单无限循环代码,但为什么输入bye,却无法结束呢?
package main
import( "bufio" "fmt" "os" "strings" )
func main(){
inputReader := bufio.NewReader(os.Stdin)
fmt.Println("Please input your name:")
input,err := inputReader.ReadString('\n')
if err!=nil{
fmt.Printf("An error occurred :%s\n", err)
os.Exit(1)
}else{
name := input[:len(input)-1]
fmt.Printf("hello,%s What can i do for you!", name)
}
for {
input,err = inputReader.ReadString('\n')
if err!=nil{
fmt.Printf("An error occurred :%s\n", err)
continue
}
input = input[:len(input)-1]
input = strings.ToLower(input)
switch input{
case "":
continue
case "bye":
fmt.Println("bye!")
os.Exit(0)
default:
fmt.Printf("Sorry,I didn't catch you.")
}
}
}
有疑问加站长微信联系(非本文作者)

单步调试,使用eclipse,input却无法查看到数据的类型,刚入坑,求高手指点
求大神啊,实在搞不清楚问题啊
测试完全正常,我估计是你eclipse的坑,你用终端 go run 一下试试
我也怀疑是eclipse的问题,谢谢大神,我试试终端看看
case "bye":改为case:string(input)
好像找到原因 了。 //划重点,下面改成input = input[:len(input)-2] 就可以了。 // input = input[:len(input)-1] input = input[:len(input)-2] input = strings.ToLower(input) switch input{ case "": continue case "bye": fmt.Println("bye!") os.Exit(0) default: fmt.Printf("Sorry,I didn't catch you.")
} } 我用编译器看了一下,我输入bye的时候,编译器统计它是5个字符,总共是bye\n,\n是换行字符,所以必须切割掉\n,总共2个字符。刚学习Go,可能表达上不是很准确,但大概就是这么个意思。
也就是把这个,改成减掉2,就可以了。input = input[:len(input)-2]
谢谢各位
谢谢哥子