[mercury-users] Accepting Values from the user

Fergus Henderson fjh at cs.mu.OZ.AU
Sat Oct 12 21:19:55 AEST 2002


On 12-Oct-2002, Noel  Pinto <cool4life at rediffmail.com> wrote:
> Below is code which squares a particular number 12. I want that 
> number to be entered by the user. But I do not know how to accept 
> integers.

Generally the best way to accept integers from the user is to read a
line of text using io__read_line_as_string, and then convert the string
to an integer using string__to_int (for `int', the limited-range
integer type) or integer__from_string (for `integer', the unbounded
integer type).

Here's an example.

:- module read_int.
:- interface.
:- import_module io.

:- pred main(io__state::di, io__state::uo) is det.

:- implementation.
:- import_module string, exception.

main -->
	print("Enter an int: "), flush_output,
	read_int(Int),
	print("You entered: "), print(Int), nl.

:- pred read_int(int::out, io__state::di, io__state::uo) is det.
read_int(Int) -->
	io__read_line_as_string(Result),
	{
		Result = ok(Line),
		remove_suffix(Line, "\n", IntString),
		string__to_int(IntString, IntVal)
	->
		Int = IntVal
	;
		% better error handling is left as an exercise for the
		% reader...
		throw("invalid entry, end-of-file, or I/O error")
	}.

-- 
Fergus Henderson <fjh at cs.mu.oz.au>  |  "I have always known that the pursuit
The University of Melbourne         |  of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh>  |     -- the last words of T. S. Garp.
--------------------------------------------------------------------------
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the users mailing list