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.
Here,
stdout
is the usual standard output text streamwrite
is a command to write a string to a nominated output text stream. We can use it for printing tostdout
as well as to files.fflush
is a command to flush any buffered output to the physical device associated with a text streamstdin
is the usual standard input text streamreadln
reads a string from a nominated input text stream, including the terminating newline if presentval
names a value, in this case that returned by thereadln
function. We will talk more about values soon.writeln
writes a string to a nominated output stream and ends a line