gpt4 book ai didi

Golang 在另一个 for 循环中退出 bufio for 循环

转载 作者:数据小太阳 更新时间:2023-10-29 03:11:49 28 4
gpt4 key购买 nike

我有一个初始循环,它不断询问用户问题,直到用户键入 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 to quit ...”,当我休息时,它会退出两个循环。

知道我应该如何解决这个问题吗?

最佳答案

很难准确地说出您想要什么,因为您没有向我们提供样本输入和输出。也许,根据您的代码,是这样的:

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"]

关于Golang 在另一个 for 循环中退出 bufio for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640461/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com