Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Converting string to integers or chars to integers

Status
Not open for further replies.

sstteevvee

Programmer
Oct 18, 2010
2
AU
Hey guys, I'm trying to get an input from the user as a string consisting only of numbers and converting it to a list of integers. I can read the string in and convert it to a list of characters but i don't know how to convert these characters to integers, or how to convert the origional string to a list of integers..? Anyways, here is my code to convert to a list of characters, is there a way to convert these to integers or a better way of achieving this??

convert :-
fmt_read("%s",X,_),
atom_chars(X,L),
write(L), nl.

eg:
$convert.
123058469
X = [1,2,3,0,5,8,4,6,9].
 
I'm not sure what fmt_read is. Which version of Prolog are you using?
 
I'm not sure, i am running it over SSH Secure Shell.

$ prolog
xsb -i
[xsb_configuration loaded]
[sysinitrc loaded]
[packaging loaded]

XSB Version 2.6 (Duff) of June 24, 2003
[sparc-sun-solaris2.9; mode: optimal; engine: slg-wam; gc: indirection; scheduling: local]

the fmt_read("%s",X,_), reads in a string from the user.
I dont have to use this, it was the only way i new how to read in a string.
 
I don't know how it works with your Prolog.
In SWI-Prolog a string is a list of codes :
?- L = "Hello World !".
L = [72,101,108,108,111,32,87,111,114,108,100,32,33].
So, in SWI-Prolog, you can do that :
?- L = "Hello World !", maplist(char_code, S, L).
L = [72,101,108,108,111,32,87,111,114,108,100,32,33],
S = ['H',e,l,l,o,' ','W',o,r,l,d,' ',!] .
.
But, if you work with a number (e.g. 123058469), it's different :
Code:
test(V) :-
    number_chars(V, LC),
    maplist(number_chars_, LD, LC),
    write(LD), nl.


number_chars_(N, C) :-
    number_chars(N, [C]).
output :
?- test(123456).
[1,2,3,4,5,6]
true

 
For a string of digits, you can find everything you need in what I wrote.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top