> < ^ Date: Wed, 26 Sep 2001 08:45:18 +0100
> < ^ From: Steve Linton <sal@dcs.st-and.ac.uk >
^ Subject: Input from User

Dear GAP Forum

"Chad T. Lower" <chadtlower@hotmail.com> asked:

I am trying to write a program that will allow the user to enter in
any number of elements after the program is run.

For example, I want to be able to ask, how many numbers will you be
entering. Suppose the user says 3. Then I want the program to accept
3 numbers. If they would have said 7, then I would want the program
to accept 7 numbers. Is GAP capable of accepting input after the
program (function) has started?

The first thing to say in response to this is -- is this what you really want?
Experience leads us to largely avoid writing interactive programs of this
kind, preferring instead to write functions which take the values from the
user as parameters. Thus

gap> myprog(1,2,3);

rather than

gap> myprog();
Enter your numbers: 1 2 3

The main reason for this is that it supports the development of further
programs that use myprog by passing arguments to it, and that it interacts
better with GAP features such as log files and command line editing.

Having said that, the basic tool for reading input from the user is streams,
described in chapter 10 of the manual. Specifically, you want to create an
input stream via InputTextUser() and read from it. For instance:

gap> s := InputTextUser();
InputTextFile(*stdin*)
gap> Print("Prompt: \c"); l := ReadLine(s);;
Prompt: This is a line of input
gap>l;
"This is a line of input\n"
gap>

Note the \c to force the output buffer to be flushed and get the partial line
"Prompt: " printed.

After this, l contains the line typed by the user as a string, and you then
need to extract (for instance) integers from it. The library functions
SplitString and Int can be useful in this. For instance:

gap> l := "1 2 3 4 5 6\n";
"1 2 3 4 5 6\n"
gap> SplitString(l," \n");
[ "1", "2", "3", "4", "5", "6" ]
gap> List(last, Int);    
[ 1, 2, 3, 4, 5, 6 ]

As you can see, multiple integers can be obtained in this way (or there are
plenty of other ways).

Steve Linton


> < [top]