【发布时间】:2017-02-21 14:19:37
【问题描述】:
您好,我在下面的 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
- 第二个问题是为什么控制流不等待用户输入就进入第二个for循环。带有“%q”的 Scanf 是否返回了 carraige return 。 任何帮助将不胜感激
【问题讨论】:
-
从输入中读取一行在 Go 中有点不直观,似乎很多初学者都偶然发现了这一点。有关如何执行此操作的示例,请参阅此问题:stackoverflow.com/q/20895552/723693
-
有趣的是,输入
data type和"data type"有一个回车少于或多于必要! :\
标签: go