A T
A T

Reputation: 13826

Continue reading stdin until "END" in Scala?

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

Upvotes: 2

Views: 2408

Answers (4)

Mike Slinn
Mike Slinn

Reputation: 8403

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")
}

Upvotes: 2

senia
senia

Reputation: 38045

You should use mkString instead of toString here:

val text = Iterator.
    continually(Console.readLine).
    takeWhile(_ != "END").
    mkString("\n")

mkString on collection aggregates all elements in a string using optional separator.

Upvotes: 5

user1484819
user1484819

Reputation: 919

I guess you want something like this:

var buffer = ""
Iterator.continually(Console.readLine).takeWhile(_ != "END").foreach(buffer += _)
val text = buffer

Upvotes: 0

Vladimir
Vladimir

Reputation: 499

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

Upvotes: 1

Related Questions