Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read from standard input line by line?

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());         }     } } 
like image 291
Andrei Ciobanu Avatar asked Jan 03 '11 15:01

Andrei Ciobanu


People also ask

What does it mean to read from standard input?

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.

Which of the following is used to read a line from the standard input?

Explanation: The raw_input([prompt]) function reads one line from standard input and returns it as a string.

How do you read a stdin line?

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.


1 Answers

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)   } } 
like image 57
itemState Avatar answered Oct 06 '22 00:10

itemState