How do I continue reading stdin
until "END" string reached, in Scala?
Here's what I've tried:
val text = Iterator.continually(Console.readLine).takeWhile(_ != "END").toString
How do I continue reading stdin
until "END" string reached, in Scala?
Here's what I've tried:
val text = Iterator.continually(Console.readLine).takeWhile(_ != "END").toString
I guess you want something like this:
var buffer = ""
Iterator.continually(Console.readLine).takeWhile(_ != "END").foreach(buffer += _)
val text = buffer
You can use simple recursion function like this:
def r(s: String = ""): String = {
val l = readLine
if (l == "END") s
else r(s + l)
}
You can call it r("")
it return result string
Conole.readLine
is deprecated. Use io.StdIn.readLine
instead. Here a complete program with your code fragment. The only change I made is that it reads the entire input, until the user presses Ctrl-D or EOF is encountered:
import io.StdIn.readLine
object Reader extends App {
val x = Iterator
.continually(readLine)
.takeWhile(_ != null)
.mkString("\n")
println(s"STDIN was: $x")
}
You should use
mkString
instead oftoString
here:mkString
on collection aggregates all elements in a string using optional separator.