我试图将串行输入解析为句子,然后将这些句子分配给变量。这是我想要做的一个例子。我的串口当前输出:
C.call
我读了这个并使用以下方式打印:
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)
我该怎么办呢?谢谢。
答案 0 :(得分:0)
从输入中收集行:
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])