如何在Golang中获取多行输入 – 面试编码

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

how to get multiple line inputs in golang - interview coding

问题

对于在golang编码面试中的以下类型的输入,最好的获取输入的方法是什么?

输入:

3
hello elloh
test estt
tier riet

我找到了两种方法:

方法1:

reader := bufio.NewReader(os.Stdin)

var lines []string

for {
	line,err := reader.ReadString('\n') //这只读取一行

	if err != nil {
		log.Fatal(err)
	}


	if len(strings.TrimSpace(line)) == 0 {
		break
	}

	line_s := strings.Split(line, " ")

	lines = append(lines, line_s...)

}

方法2:

bytes, err := ioutil.ReadAll(os.Stdin)

fmt.Println(len(bytes))
if err == nil {
	input := strings.Split(string(bytes), "\n")
	count, _ := strconv.Atoi(input[0])

	fmt.Println(input)
	var lines []string
	for i := 1; i < count; i++ {
		line := strings.Split(input[i], " ")
		lines = append(lines, line...)
	}

	fmt.Println(lines)
}

但是不确定如何在方法2中结束从stdin获取输入。

请建议获取输入的最佳方法。

英文:

For the below type of inputs in golang coding interviews, what is the best way to get the input?

Input:

3
hello elloh
test estt
tier riet

I found two methods:

Method 1:

reader := bufio.NewReader(os.Stdin)

var lines []string

for {
	line,err := reader.ReadString(&#39;\n&#39;) //this reads only one read

	if err != nil {
		log.Fatal(err)
	}


	if len(strings.TrimSpace(line)) == 0 {
		break
	}

	line_s := strings.Split(line, &quot; &quot;)

	lines = append(lines, line_s...)

}

Method 2:

bytes, err := ioutil.ReadAll(os.Stdin)

fmt.Println(len(bytes))
if err == nil {
	input := strings.Split(string(bytes), &quot;\n&quot;)
	count, _ := strconv.Atoi(input[0])

	fmt.Println(input)
	var lines []string
	for i := 1; i &lt; count; i++ {
		line := strings.Split(input[i], &quot; &quot;)
		lines = append(lines, line...)
	}

	fmt.Println(lines)
}

But not sure how to end getting input from stdin in Method2.

Please suggest the best method to get input.

答案1

得分: 1

使用bufio.Scanner来读取输入。使用一个函数来封装复杂性和实现细节。例如,

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func readData(s *bufio.Scanner) ([][]string, error) {
	var data [][]string
	if !s.Scan() {
		return nil, s.Err()
	}
	nLine, err := strconv.Atoi(strings.TrimSpace(s.Text()))
	if err != nil {
		return nil, err
	}
	for ; nLine > 0 && s.Scan(); nLine-- {
		data = append(data, strings.Fields(s.Text()))
	}
	if err := s.Err(); err != nil {
		return nil, err
	}
	if nLine != 0 {
		err := fmt.Errorf("missing %d lines of data", nLine)
		return nil, err
	}
	return data, nil
}

func main() {
	s := bufio.NewScanner(os.Stdin)

	data, err := readData(s)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	fmt.Println(len(data))
	for _, datum := range data {
		fmt.Println(datum)
	}
}

链接:https://go.dev/play/p/0Xwp3-hwGyK

3
hello elloh
test estt
tier riet
3
[hello elloh]
[test estt]
[tier riet]
英文:

Use bufio.Scanner to read input. Use a function to encapsulate complexity and implementation details. For example,

package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;strconv&quot;
	&quot;strings&quot;
)

func readData(s *bufio.Scanner) ([][]string, error) {
	var data [][]string
	if !s.Scan() {
		return nil, s.Err()
	}
	nLine, err := strconv.Atoi(strings.TrimSpace(s.Text()))
	if err != nil {
		return nil, err
	}
	for ; nLine &gt; 0 &amp;&amp; s.Scan(); nLine-- {
		data = append(data, strings.Fields(s.Text()))
	}
	if err := s.Err(); err != nil {
		return nil, err
	}
	if nLine != 0 {
		err := fmt.Errorf(&quot;missing %d lines of data&quot;, nLine)
		return nil, err
	}
	return data, nil
}

func main() {
	s := bufio.NewScanner(os.Stdin)

	data, err := readData(s)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	fmt.Println(len(data))
	for _, datum := range data {
		fmt.Println(datum)
	}
}

https://go.dev/play/p/0Xwp3-hwGyK

3
hello elloh
test estt
tier riet
3
[hello elloh]
[test estt]
[tier riet]

huangapple
  • 本文由 发表于 2023年2月4日 08:26:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75342213.html
匿名

发表评论

匿名网友

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

确定