ExpandCollapsePrev Next Index

+ 4.1 Reading Standard Streams

Another way to get some data in is to leverage the standard input/output streams. We've already used the output stream to display data (using print and println), but let's try something new and "capture" data via standard input.

  write$ stdout,"Enter your name: "; fflush stdout;
  val name = readln$ stdin;
  writeln$ stdout, "Hello " + name;

Felix the Cat

Enter your name: Felix the Cat
Hello Felix the Cat

You might wonder if there any difference between print x and write$ stdout, x; fflush stdout;?

There is, but it's subtle.

print and it's kin are designed for fast output to the console. They write the strings to stdout the same as write$ stdout, ... does, however it does not force the buffer to flush. If it did, the program would have to wait for the console to display the content before proceeding, and this could be slow.

Most of the time we can let the console manage its own output buffering, but when we want to ask the user a question, it's better to be sure the question is displayed before querying for input. If we leave this out it just looks like the program is stuck trying to print, when it's actually waiting for the user. So, we can say fflush stdout; makes sure the content is displayed.


  • stdout is the usual standard output text stream
  • write is a command to write a string to a nominated output text stream. We can use it for printing to stdout as well as to files.
  • fflush is a command to flush any buffered output to the physical device associated with a text stream
  • stdin is the usual standard input text stream
  • readln reads a string from a nominated input text stream, including the terminating newline if present
  • val names a value, in this case that returned by the readln function. We will talk more about values soon.
  • writeln writes a string to a nominated output stream and ends a line