# 1.21 Getting a string from the keyboard

Of course, you don't want to initialize strings all your life. Real applications get their input from the keyboard. We've already shown you how to get a number from the keyboard. Now we turn to strings.

When programming in BASIC, strings usually have an undefined length. Some BASICs move strings around in memory, others have to perform some kind of "garbage-collection". Whatever method they use, it takes up memory and processor-time.

4tH forces you to think about your application. E.g. when you want to store somebodies name in a string variable, 16 characters will be too few and 512 characters too many. But 64 characters will probably do.

But that poses a problem when you want to get a string from the keyboard. How can you prevent that somebody types a string that is just too long? And how do you terminate it?

The word 'ACCEPT' takes two arguments. First, the string variable where you want to save the input and second, the maximum number of characters it can take. It automatically terminates the string when reading from the keyboard. But there is a catch. This program can get you into trouble:

         64 constant #name               \ length of string
         #name string name               \ define string 'name'

         name #name accept               \ input string
         name swap type cr               \ swap count and print

Since 64 characters *PLUS* the terminator add up to 65 characters. You will probably want to use this definition instead:

         variable span                   \ will hold count
         : expect 1- accept span ! ;     \ define 'EXPECT'

         64 constant #name               \ length of string
         #name string name               \ define string 'name'

         name #name expect               \ input string
         name count type cr              \ print string

The word 'EXPECT' is an old favorite of us, although it is declared "obsolete" in the ANS-Forth standard. This version decrements the count so the user input will fit nicely into the string variable.

The word 'ACCEPT' always returns the number of characters it received. You will find that you won't need that information most of the time. 'EXPECT' saves that information in a variable called 'SPAN'. If you need it, it's there.

This is the end of the second level. Now you should be able to understand most of the example programs and write simple ones. I suggest you do just that. Experience is the best teacher after all.