嗨,我在以下Go程序中遇到两个问题。
1.我无法使用Scanf或Scanln读取空格分隔的字符串。
因此,我添加了格式化的字符串"%q"以使用双引号读取空格分隔的字符串。
有替代方法来读取带空格的字符串吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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) } } |
控制台输出如下,
1 2 3 4 5 | VenKats-MacBook-Air:ColumnCreator venkat$ go run test.go Enter the DataType "rid bigint not null" Enter the Table Enter a valid Table name |
任何帮助将不胜感激
- 在Go语言中,从输入中读取一行内容并非直觉,似乎很多初学者都迷失了这一点。请参见以下问题,以获取有关如何执行此操作的示例:stackoverflow.com/q/20895552/723693
-
有趣的是,输入
data type 和"data type" 的回车符小于或大于必填项! :\\\\
也许是这样。.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 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('\ ') // 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\ ", err.Error()) } } for { fmt.Println("Enter the Table") text, err := cin.ReadString('\ ') if strings.TrimSpace(text) =="" { continue } if err == nil { dt.Table = text break } else { fmt.Printf("An error as occured: %s\ ", err.Error()) } } fmt.Printf("%+v\ ", dt) return } |
重构代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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('\ ') if strings.TrimSpace(input) =="" { continue } if err == nil { break } else { fmt.Printf("An error as occured: %s\ ", 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\ ", dt) return } |