我有一个初始循环,一直询问用户问题,直到用户键入q退出。
func main() {
scanner := bufio.NewScanner(os.Stdin)
quit := false
var city string
var anything string
for quit == false {
fmt.Println("Enter a city name")
for scanner.Scan(){
city= scanner.Text()
fmt.Printf("q to quit (Anything else to continue): ")
anything = scanner.Text()
}
if anything == "q" {
fmt.Println(city)
quit = true
}
}
}
我正在努力弄清楚我是如何退出扫描仪的嵌套for循环并继续使用初始for循环直到用户输入q。现在,它不会退出第二个循环,所以它总是提示“q退出...”,当我休息时它会退出两个循环。
知道我应该如何解决这个问题吗?
答案 0 :(得分:1)
很难确切地说出你想要什么,因为你没有向我们提供样本输入和输出。也许,根据您的代码,这样的事情:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
var cities []string
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Println("Enter a city name")
if !scanner.Scan() {
break
}
city := scanner.Text()
if len(city) > 0 {
cities = append(cities, city)
}
fmt.Printf("q to quit (Anything else to continue): ")
if !scanner.Scan() || scanner.Text() == "q" {
break
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
fmt.Printf("%q\n", cities)
}
输出:
Enter a city name
Los Angeles
q to quit (Anything else to continue):
Enter a city name
London
q to quit (Anything else to continue):
Enter a city name
Delhi
q to quit (Anything else to continue): q
["Los Angeles" "London" "Delhi"]