我正在尝试将串行输入解析成句子,然后将这些句子赋给一个变量。下面是我正在尝试做的一个例子。我的串口当前输出如下:
This is the first sentence.
This is the second sentence.
This is the third sentence.
我读到了这篇文章,并使用以下命令打印出来:
scanner := bufio.NewScanner(port)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
我想要做的是将每个句子赋给一个新的变量,。我想稍后做一些类似这样的事情(示例):
fmt.Printf("First sentence: %q\n", firstSen)
fmt.Printf("Second sentence: %q\n", secondSen)
fmt.Printf("Third sentence: %q\n", thirdSen)
并且它应该输出:
First sentence: This is the first sentence.
Second sentence: This is the second sentence.
Third sentence: This is the third sentence.
我该如何着手做这件事?谢谢。
发布于 2018-06-01 06:22:22
从输入中收集行:
var lines []string
scanner := bufio.NewScanner(port)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
// handle error
}
遍历变量并将一行赋值给该变量:
var firstSen, secondSen, thirdSen string
for i, s := range []*string{&firstSen, &secondSen, &thirdSen} {
if i >= len(lines) {
break
}
*s = lines[i]
}
按照问题中所示打印:
fmt.Printf("First sentence: %q\n", firstSen)
fmt.Printf("Second sentence: %q\n", secondSen)
fmt.Printf("Third sentence: %q\n", thirdSen)
根据您的需求,您可以删除变量并直接使用代码段:
fmt.Printf("First sentence: %q\n", line[0])
fmt.Printf("Second sentence: %q\n", line[1])
fmt.Printf("Third sentence: %q\n", line[2])
https://stackoverflow.com/questions/50633207
复制相似问题