2.2. greet.bas

[<<<] [>>>]

After you have seen how to write to the screen this is the next step to read from the keyboard. Reading from the keyboard is common in small programs that require complex parameters that do not easily fit on the command line as parameters or want to help the user with screen prints what to enter. Lets see the first example!

Example greet1.bas :

PRINT "What is your name?"
PRINT
LINE INPUT Name$
PRINT "HELLO ",Name$," my deer"

This program prints the string What is your name?> on the screen using the statement @code{PRINT, which should already familiar to you. The next statement prints a new-line, thus the cursor is now below the printed string. At this point the program executes the command LINE INPUT. This command reads from the keyboard (from the standard input to be precise) until the end of the line. In other words the command reads the characters that you type up to and including the new-line character you typed by pressing the line terminating ENTER. Let's see what the result is running this program!

Result executing greet1.bas :

in case your name is Peter and you typed it at keyboard when the program questioned. The command LINE INPUT reads a line from the standard input. This is usually the keyboard. The line is put into a variable, that is named Name$ in our example. Notice that the whole line, including the terminating new-line is put into the variable. This is the reason, why the string my deer gets on the next line and not just after the name.

In case you want to get rid of the string terminating new line you can use the function CHOMP.

Example greet2.bas :

PRINT "What is your name?"
PRINT
LINE INPUT Name$
Name$ = CHOMP(Name$)
PRINT "HELLO ",Name$," my deer"

Result executing greet2.bas :

The function CHOMP removes the trailing new-line characters from the end of a string and returns the string without them. This could be performed using other functions, but this function was designed for the very purpose and thus it is very convenient. If the string does not happen to have a new-line character at the end no harm is done. CHOMP removes the last character only if the character is new-line.

The command LINE INPUT can also be used to read lines from files, but that issue is a bit more complex and will be discussed later.

There is also a function called INPUT, which reads from the standard input or from a file given number of characters (or rather bytes to be precise). This will also be detailed later.


[<<<] [>>>]