douxie9347 2017-02-19 04:15
浏览 362
已采纳

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

Hi I have two problems in the following Go Program .
1. I couldn't read the space seperated string using Scanf or Scanln.
So I have added a formatted string "%q" to read space seperated string using double quotes. Is there an alternative to read string with spaces ?

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)
    }
}

The Console output is as follows ,

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. The Second problem is why does the control flow went to the second for loop without waiting for the user input . Does the Scanf with "%q" returned a carraige return . Any help would be greatly appreciated
  • 写回答

1条回答 默认 最新

  • duanmeng1862 2017-02-21 06:19
    关注

    Perhaps something like this..

    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
    }
    

    Example of refactored code:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同