How to add two strings together?

Pixilang programming language
Post Reply
philipbergwerf
Posts: 174
Joined: Sat Mar 17, 2018 4:23 pm

How to add two strings together?

Post by philipbergwerf »

I tried:

Code: Select all

str1 = "A#"
str2 = "4"
together = str1 + str2
printf("%s\n", together)
This gives number 7 as result. Is it possible in pixilang?
User avatar
NightRadio
Site Admin
Posts: 3941
Joined: Fri Jan 23, 2004 12:28 am
Location: Ekaterinburg. Russia
Contact:

Re: How to add two strings together?

Post by NightRadio »

str1 = "A#"
str2 = "4"
together = str1 + str2
Don't forget that everything is numbers in Pixilang :)
str1 = ID of some container (with text)
str2 = container ID too
together = str1 + str2 - just a sum of two numbers
Then you write: printf("%s\n", together)
%s expects the container ID with a string, but you give it some random number, so printf() tries to find a container with that number and display its contents as text.

The right ways:

Code: Select all

str1 = "A#"
str2 = "4"
together = ""
strcat( together, str1 )
strcat( together, str2 )

Code: Select all

str1 = "A#"
str2 = "4"
together = ""
sprintf( together, "%s%s", str1, str2 )
philipbergwerf
Posts: 174
Joined: Sat Mar 17, 2018 4:23 pm

Re: How to add two strings together?

Post by philipbergwerf »

Why is this piece of code resulting in adding the previous result to the string?

Code: Select all

fn function()
{
    $scale = 5
    t_scale( $scale, $scale, $scale )
    $note = "A#"
    $octn = "4"
    $together = ""
    strcat( $together, $note )
    strcat( $together, $octn )
    print($together,0,0,RED)
    t_reset()
}

while 1
{
    clear()
    
    // draw text over and over each frame
    function()
    
    while( get_event() )
    {
        if EVT[EVT_TYPE] == EVT_QUIT { halt }
    }
    frame()
}
on line 7 (would it be a good idea to have line numbers inside the forum code view?) I clearly create every time a new empty string. Why is it keeping the previous value while line 7 is putting local variable $together to 'empty string'?
User avatar
NightRadio
Site Admin
Posts: 3941
Joined: Fri Jan 23, 2004 12:28 am
Location: Ekaterinburg. Russia
Contact:

Re: How to add two strings together?

Post by NightRadio »

Code: Select all

$note = "A#"
$octn = "4"
$together = ""
Here the new strings are created only once when the program is compiled.
The compiler reads each string and creates a container for it.
Then it turns the above code into something like this:

Code: Select all

$note = 10
$octn = 11
$together = 12
So every time you call function(), $together points to the same string container. And then strcat() adds more text to the end of that container.

Try this:

Code: Select all

$note = "A#"
$octn = "4"
$together = ""
$together[ 0 ] = 0 //null character specifies the end of the string
strcat( $together, $note )
strcat( $together, $octn )
Post Reply