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
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.
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.
stdoutis the usual standard output text stream
writeis a command to write a string to a nominated output text stream. We can use it for printing to
stdoutas well as to files.
fflushis a command to flush any buffered output to the physical device associated with a text stream
stdinis the usual standard input text stream
readlnreads a string from a nominated input text stream, including the terminating newline if present
valnames a value, in this case that returned by the
readlnfunction. We will talk more about values soon.
writelnwrites a string to a nominated output stream and ends a line