gpt4 book ai didi

go - 在 Golang 1.8 中读取空格分隔的字符串

转载 作者:IT王子 更新时间:2023-10-29 02:12:29 32 4
gpt4 key购买 nike

你好我在下面的 Go 程序中有两个问题。
1. 我无法使用 Scanf 或 Scanln 读取空格分隔的字符串。
所以我添加了一个格式化字符串“%q”来使用双引号读取空格分隔的字符串。是否有替代方法来读取带空格的字符串?

package main
import
(
"fmt"
"strings"
)

type details struct{
DataType string
Table string

}
func main(){
dt := details{}
fmt.Println("Enter the DataType")
fmt.Scanf("%q" ,&dt.DataType )
for strings.TrimSpace(dt.DataType) == "" {
fmt.Println("Enter the DataType")
fmt.Scanln(&dt.DataType)
}
//fmt.Println(dt.DataType)
fmt.Println("Enter the Table")
fmt.Scanln(&dt.Table)
for strings.TrimSpace(dt.Table) == "" {
fmt.Println("Enter a valid Table name ")
fmt.Scanln(&dt.Table)
}
}

控制台输出如下,

VenKats-MacBook-Air:ColumnCreator venkat$ go run test.go
Enter the DataType
"rid bigint not null"
Enter the Table
Enter a valid Table name
  1. 第二个问题是为什么控制流不等待用户输入就进入第二个for循环。带有“%q”的 Scanf 是否返回了 carraige return 。任何帮助将不胜感激

最佳答案

也许是这样的..

package main

import (
"bufio"
"fmt"
"os"
"strings"
)

type details struct {
DataType string
Table string
}

func main() {
dt := details{}
cin := bufio.NewReader(os.Stdin)
for {
fmt.Println("Enter the DataType")
text, err := cin.ReadString('\n') // reads entire string up until the /n which is the newline deliminator
if strings.TrimSpace(text) == "" { // check to see if the input is empty
continue
}
if err == nil { // if the input is not empty then the control got this far and now we just have to check for error, assign the data, and break out of the loop .. repeat for the second input. If this is going to be something you do alot refactor the input section.
dt.DataType = text
break
} else {
fmt.Printf("An error as occured: %s\n", err.Error())
}
}
for {
fmt.Println("Enter the Table")
text, err := cin.ReadString('\n')
if strings.TrimSpace(text) == "" {
continue
}
if err == nil {
dt.Table = text
break
} else {
fmt.Printf("An error as occured: %s\n", err.Error())
}
}
fmt.Printf("%+v\n", dt)
return
}

重构代码示例:

package main

import (
"bufio"
"fmt"
"os"
"strings"
)

type details struct {
DataType string
Table string
}

func getInput(message string, reader bufio.Reader) (input string) {
for {
fmt.Println(message)
input, err := reader.ReadString('\n')
if strings.TrimSpace(input) == "" {
continue
}
if err == nil {
break
} else {
fmt.Printf("An error as occured: %s\n", err.Error())
}
}
return
}

func main() {
dt := details{}
cin := bufio.NewReader(os.Stdin)
t := getInput("Enter the DataType", *cin)
dt.DataType = t
t = getInput("Enter the Table", *cin)
dt.Table = t
fmt.Printf("Seeing what my data looks like %+v\n", dt)
return
}

关于go - 在 Golang 1.8 中读取空格分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42323567/

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