Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Manipulating characters



Using read() and write() we can read or write the value of atoms, predicates, strings, etc. Now in this section we will see how to write single characters into the current output stream, or how to read from current input stream. So there are some predefined predicates to do these tasks.

The put(C) and put_char(C) predicates

We can use put(C) to write one character at a time into the current output stream. The output stream can be a file or the console. This C can be a character or an ASCII code in other version of Prolog like SWI prolog, but in GNU prolog, it supports only the ASCII value. To use the character instead of ASCII, we can use put_char(C).

Program

| ?- put(97),put(98),put(99),put(100),put(101).
abcde

yes
| ?- put(97),put(66),put(99),put(100),put(101).
aBcde

yes
| ?- put(65),put(66),put(99),put(100),put(101).
ABcde

yes
| ?- put_char('h'),put_char('e'),put_char('l'),put_char('l'),put_char('o').
hello

yes
| ?-

The get_char(C) and get_code(C) predicates

To read a single character from the current input stream, we can use the get_char(C) predicate. This will take the character. if we want the ASCII code, we can use get_code(C).

Program

| ?- get_char(X).
A.

X = 'A'

(16 ms) yes
uncaught exception: error(syntax_error('user_input:1 (char:14) expression expected'),read_term/3)
| ?- get_code(X).
A.

X = 65

(15 ms) yes
uncaught exception: error(syntax_error('user_input:2 (char:14) expression expected'),read_term/3)
| ?- 
prolog_inputs_and_outputs.htm
Advertisements