8

So as the title says - how do you convert a string into an integer? the idea is something like this:

convert(String,Integer).

examples:
convert('1',1).
convert('33',33).

I'm using swi prolog

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
Iva
  • 81
  • 1
  • 1
  • 2
  • 3
    possible duplicate of [Parsing numbers with multiple digits in Prolog](http://stackoverflow.com/questions/3279822/parsing-numbers-with-multiple-digits-in-prolog) – Ted Hopp Jul 21 '11 at 20:05
  • 2
    @Ted Hopp: not a dupe, the other question has the specific context of DCGs. This can be done more easily. The OP has to decide whether a string or an atom is given, though. – Fred Foo Jul 21 '11 at 20:24

6 Answers6

16

Use atom_number/2. E.g:

  atom_number('123', X).
  X = 123.
gusbro
  • 22,357
  • 35
  • 46
12

Assuming you really meant a string and not an atom, use number_codes.

?- number_codes(11, "11").
true.

?- number_codes(11, Str).
Str = [49, 49].            % ASCII/UTF-8

?- number_codes(N, "11").
N = 11.
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
5

Perhaps use of atom_codes(?Atom, ?String) and number_chars(?Number, ?CharList) would do it.

MRAB
  • 20,356
  • 6
  • 40
  • 33
2

Quite an old, but there is a predicate in SWI Prolog: number_string(N, S).

Docs

number_string(123, S).
S = "123".

For those who are still looking for it.

Omar
  • 105
  • 1
  • 3
  • 12
0
A simple example using Visual Prolog 10
==============================
% UNS-EPISI-LAB-IA

implement main
    open core

clauses
    run() :-
        console::write("Valor de A? "),
        A = console::readLine(),
        console::write("Valor de B? "),
        B = console::readLine(),
        Areal = toTerm(real, A),
        Breal = toTerm(real, B),
        console::write("A + B = ", Areal + Breal),
        _ = console::readChar().

end implement main

goal
    console::runUtf8(main::run).
Karman
  • 1
  • 1
  • Welcome to SO! Good solution, but I think it isn't quite relevant, because OP explicitly asked for SWI-Prolog solution. – hurufu Dec 13 '22 at 16:04
-1

in Visual Prolog convert:

X=toTerm(real,H).

real/integer/unsigned...

Drovosek
  • 99
  • 4