B03) Why does getInt followed by getLine not necessarily work as expected?
Description
This article is from the FAQ, by with numerous contributions by
others.
B03) Why does getInt followed by getLine not necessarily work as expected?
You have to be careful when scanning input entered from the keyboard. For
example, if your program has a section of the form
keyboard.getInt->...;
...
keyboard.getLine->...;
and you enter, say,
42<return>
foo<return>
then the string returned by keyboard.getLine will be empty because getInt
stops scanning immediately after 42 and does not consume the (non-numeric)
new-line character. [Thus, entering
42foo<return>
works correctly.] You may insert the line
(if keyboard.peek=ascii.newline then keyboard.get if);
between the calls to getInt and getLine to get the desired effect, or even
call
keyboard.scanWhiteSpace
in which case, however, you won't be able to enter a string starting with
white-space characters, similar to the functionality of C's library function
scanf().
 
Continue to: