What's the Scala recipe for reading line by line from the standard input ? Something like the equivalent java code :
import java.util.Scanner; public class ScannerTest { public static void main(String args[]) { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ System.out.println(sc.nextLine()); } } }
Updated: 08/02/2020 by Computer Hope. Short for standard input, stdin is an input stream where data is sent to and read by a program. It is a file descriptor in Unix-like operating systems, and programming languages, such as C, Perl, and Java.
Explanation: The raw_input([prompt]) function reads one line from standard input and returns it as a string.
The gets() function reads a line from the standard input stream stdin and stores it in buffer. The line consists of all characters up to but not including the first new-line character (\n) or EOF. The gets() function then replaces the new-line character, if read, with a null character (\0) before returning the line.
The most straight-forward looking approach will just use readLine()
which is part of Predef
. however that is rather ugly as you need to check for eventual null value:
object ScannerTest { def main(args: Array[String]) { var ok = true while (ok) { val ln = readLine() ok = ln != null if (ok) println(ln) } } }
this is so verbose, you'd rather use java.util.Scanner
instead.
I think a more pretty approach will use scala.io.Source
:
object ScannerTest { def main(args: Array[String]) { for (ln <- io.Source.stdin.getLines) println(ln) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With