Logo

Programming-Idioms

  • JS
  • Ruby
  • Python
  • Go

Idiom #279 Read list of strings from the standard input

Read all the lines (until EOF) into the list of strings lines.

import "bufio"
import "os"
var lines []string
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
	line := s.Text()
	lines = append(lines, line)
}
if err := s.Err(); err != nil {
	log.Fatal(err)
}

WARNING: this works only for lines smaller than 64kB each.
lines = readlines

run and enter some words in a terminal. End by Ctrl-D (EOF).
import sys
lines = sys.stdin.readlines()
from sys import stdin
lines = [*stdin]

This will include the new-line delimiter.
from sys import stdin
lines = [x.rstrip() for x in stdin]
with Ada.Text_IO;
with Ada.Containers.Indefinite_Vectors;
declare
   package String_Vectors is new
      Ada.Containers.Indefinite_Vectors
         (Index_Type => Positive, Element_Type => String);
   use String_Vectors, Ada.Text_IO;
   Lines : Vector;
begin
   while not End_Of_File loop
      Lines.Append (Get_Line);
   end loop;
end;

New implementation...