0

I need get all user input in stdin as single string in scala 2.12 (supposed the data would copy-pasted by single action), something like this:

please copy data:
word1
word2
word3

And I need get string with following data:

val str = "word1\nword2\nword3"

my current approach is not working, just hanging forever:

import scala.collection.JavaConverters._
val scanner: Iterator[String] = new Scanner(System.in).asScala

val sb = new StringBuilder
while (scanner.hasNext) {
  sb.append(scanner.next())
}
val str = sb.toString()

Although this can print the input:

import scala.collection.JavaConverters._
val scanner: Iterator[String] = new Scanner(System.in).asScala

scanner foreach println

I'm looking for idiomatic way of doing the job

Normal
  • 1,347
  • 4
  • 17
  • 34

1 Answers1

2

Try

LazyList
  .continually(StdIn.readLine())
  .takeWhile(_ != null)
  .mkString("\n")

as inspired by https://stackoverflow.com/a/18924749/5205022

On my machine I could terminate the input with ^D.

In Scala 2.12 replace LazyList with Stream.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
  • thanks for the answer, but this doesn't work for me properly. Btw what is LazyList? I used Iterator.continually instead but it is hanging forever unless I introduced special ending character – Normal Jul 28 '19 at 16:01
  • ohh I realised it is a new collection from scala 2.13, does it make difference vs Iterator ? – Normal Jul 28 '19 at 16:02
  • 2
    @Normal In Scala 2.12, just replace `LazyList` with `Stream`. In what way is it not working properly, that is, what error are you getting? – Mario Galic Jul 28 '19 at 16:09