I'd like to read longer text using Golang stdin

I want to input and read a string of more than 10000 characters using Golang’s stdin module.

However, with my current knowledge of Golang, I can only read first 4096 characters.

So I would like to anyone to help me for fixing of this problem.

Thank you.

What is your current approach? Actually, there should be no boundary on how much you can read on stdin.

It should be possible to read os.Stdin using os.ReadAll.

package main

import (
	"io"
	"os"
)

func main() {
	res, err := io.ReadAll(os.Stdin)
	if err != nil {
		panic(err)
	}

	println(len(res))
}

It reads Stdin into a buffer and appeds it to a result buffer until an error occurs. If the error is io.EOF, it returns the collected buffer. Otherwise, the error is returned. It works a bit like the following snippet.

package main

import (
	"io"
	"os"
)

func main() {
	buf := make([]byte, 1024)
	var res []byte

	for {
		n, err := os.Stdin.Read(buf)
		res = append(res, buf[:n]...)
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}
	}

	println(len(res))
}

I hope that was somewhat helpful.

Hello, @zekro
First, thank you for your reply.

I’m trying to complete this hackerrank task: Goodland Electricity

But for this test case, I need to read 100000 characters from StdIn, first.

So if possible, I’d like you to help me for fixing of this test case.

Thank you.[quote=“devphoenix092, post:1, topic:34591, full:true”]
I want to input and read a string of more than 10000 characters using Golang’s stdin module.

However, with my current knowledge of Golang, I can only read first 4096 characters.

So I would like to anyone to help me for fixing of this problem.

Thank you.
[/quote]

  • If you need to process the input line by line, using bufio.Reader is more suitable.
  • If you need to read the entire input as a single string and memory usage isn’t a concern, io.ReadAll is simpler.