include "$/inc/console.inc"
macro do_sprintf(format, ...)
indexbase 0
sys p=@param[1] 'current param pointer
string s=nuls 300 'output buffer
string v 'value string
byte bs at strptr fmt 'bytes source
byte bd at strptr s 'bytes dest
sys id=1 'output buffer index
sys sy=sizeof sys 'stack width = 4bytes/8bytes
sys lv 'length of value string
do
lv=1 'default
select bs
case 0
bd=0
exit do
case "%"
@bs++
select bs
case "i","d" : int u at p : v=str(round(u)) : p+=sy : mid(s,id)=v : lv=len v
case "g" : float u at p : v=str(u) : p+=sy : mid(s,id)=v : lv=len v
case "f" : double u at p : v=str(u) : p+=sizeof u : mid(s,id)=v : lv=len v
case "s" : char u at *p : p+=sy : mid(s,id)=u : lv=len u
case "x" : char u at *p : p+=sy : mid(s,id)="0x" & u : lv=len(u)+2
case else : bd=bs
end select
case "\"
@bs++
select bs
case "t" : bd=9
case "n" : bd=10
case else : bd=bs
end select
case else : bd=bs
end select
@bs++ : @bd+=lv : id+=lv 'NEXT POSITIONS
end do
id-=1
end macro
function sprintf(char* fmt,...) as string
=========================================
do_sprintf(fmt, ...)
return left s,id
end function
sub printf(char* fmt,...)
=========================
do_sprintf(fmt,...)
print left s,id
end sub
print sprintf "string=%s\ndouble=%f\n","abcdef",-123.45E1
printf "string=%s\ndouble=%f\n","abcdef",-123.45E1
'TEST
'====
printf("\nA very basic printf procedure", "and therefore not foolproof") ' mini joke
printf(`\nnot %d%% "safe"\n`, 100)
printf(42)
printf("\n%d\n",1+3)
printf "The Eiffel Tower is located in %s\nand it's height is %d ft.\n", "Paris", 986
printf "To Pi = %s or not to Pi = %s\n", str(pi,3), str(-pi,4)
float x=1.5f
double x1= x
printf ("x = %g\n", x)
printf ("false x = %f", x) ' false
printf ("\ncorrect x1 = %f\n", x1)
printf ("10011 = hex %x\n", hex 10011 )
printf ("The End\n")
print "Enter ...": waitkey()