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

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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
ohh I realised it is a new collection from scala 2.13, does it make difference vs Iterator ?
@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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.