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

huangapple go评论93阅读模式
英文:

Read Space Seperated Strings in Golang 1.8

问题

你好,以下是你提供的Go程序的翻译:

package main
import (
    "fmt"
    "strings"
)

type details struct{
    DataType string
    Table string
}

func main(){
    dt := details{}
    fmt.Println("请输入数据类型")
    fmt.Scanf("%q", &dt.DataType)
    for strings.TrimSpace(dt.DataType) == "" {
        fmt.Println("请输入数据类型")
        fmt.Scanln(&dt.DataType)
    }
    fmt.Println("请输入表名")
    fmt.Scanln(&dt.Table)
    for strings.TrimSpace(dt.Table) == "" {
        fmt.Println("请输入有效的表名")
        fmt.Scanln(&dt.Table)
    }
}

控制台输出如下:

VenKats-MacBook-Air:ColumnCreator venkat$ go run test.go
请输入数据类型
"rid bigint not null"
请输入表名
请输入有效的表名

第一个问题是,为什么使用ScanfScanln无法读取带有空格的字符串。为了读取带有空格的字符串,你添加了格式化字符串%q并使用双引号。是否有其他方法可以读取带有空格的字符串?

第二个问题是,为什么控制流在等待用户输入之前就进入了第二个for循环。是不是Scanf使用%q返回了一个回车符?任何帮助将不胜感激。

英文:

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

得分: 1

也许可以这样写:

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("输入数据类型")
		text, err := cin.ReadString('\n') // 读取直到换行符的整个字符串
		if strings.TrimSpace(text) == "" { // 检查输入是否为空
			continue
		}
		if err == nil { // 如果输入不为空,则进行赋值并跳出循环,对第二个输入进行相同操作。如果这是你经常做的事情,请重构输入部分。
			dt.DataType = text
			break
		} else {
			fmt.Printf("发生错误:%s\n", err.Error())
		}
	}
	for {
		fmt.Println("输入表名")
		text, err := cin.ReadString('\n')
		if strings.TrimSpace(text) == "" {
			continue
		}
		if err == nil {
			dt.Table = text
			break
		} else {
			fmt.Printf("发生错误:%s\n", err.Error())
		}
	}
	fmt.Printf("%+v\n", dt)
	return
}

重构后的代码示例

```go
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("发生错误:%s\n", err.Error())
		}
	}
	return
}

func main() {
	dt := details{}
	cin := bufio.NewReader(os.Stdin)
	t := getInput("输入数据类型", *cin)
	dt.DataType = t
	t = getInput("输入表名", *cin)
	dt.Table = t
	fmt.Printf("查看我的数据 %+v\n", dt)
	return
}
英文:

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('\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
}

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('\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
}

huangapple
  • 本文由 发表于 2017年2月19日 12:15:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/42323567.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定