Logo

Programming-Idioms

  • Pascal
  • Rust
  • Java

Idiom #278 Read one line from the standard input

Read one line into the string line.

Explain what happens if EOF is reached.

import java.util.Scanner;
String line = null;
Scanner in = new Scanner(System.in);
if(in.hasNextLine())
    line = in.nextLine();

On EOF, nextLine() would throw NoSuchElementException
import java.util.Scanner;
Scanner s = new Scanner(System.in);
String line = s.nextLine();
s.close();

The `nextLine` method will throw `NoSuchElementException` when no line is found, and `IllegalStateException` when the scanner is closed.
readln(line);

processing reading the inputs stops when EOF is reached.
let mut buffer = String::new();
let mut stdin = io::stdin();
stdin.read_line(&mut buffer).unwrap();

String is empty if EOF
with Ada.Text_IO;
Line : constant String := Ada.Text_IO.Get_Line;

End_Error is raised if EOF is reached.

New implementation...
< >
programming-idioms.org