Page 1 of 1

Char and int concatenation?

PostPosted: Mon May 20, 2013 2:24 pm
by Lacotemale
I am looking for ways to optimize my functions using more logical code. All I want to do is assemble the correct line for setting defense of an item.

Currently I have this:

Code: Select all
    const char *name = "item";
    const char *param = ".defense";
    char buf[32];
    sprintf( buf, "%s%d%s", name, selectedItem, param );

    defense = buf;
 


However it seems to give random numbers as the result, any reason for this? :shock:

Re: Char and int concatenation?

PostPosted: Mon May 20, 2013 6:46 pm
by skydereign
If defense is a char*, you can't set strings equal to each other like that. You need to use strcpy or sprintf.
Code: Select all
strcpy(defense, buf);

Re: Char and int concatenation?

PostPosted: Mon May 20, 2013 8:18 pm
by Lacotemale
Oh sorry, should have said that defense is an int value. :D

Im just trying to produce something like this:

item100.defense //this is an int value


The middle number will be an int. I have tried various things tonight but I get a value defense of 15 and I also got -33. Neither is correct. :?

Here is my latest attempt:

Code: Select all
char buf[32];
defense = sprintf( buf, "item%d.defense", selectedItem) - '0';

Re: Char and int concatenation?

PostPosted: Mon May 20, 2013 8:26 pm
by skydereign
So you want to set the integer defense equal to "item100.defense"? That doesn't make sense, since integers can only hold numbers. Perhaps item100 supposed to be an actor, and this is an actor variable? I'm rather lost as to what you want to do. Tell me the values of the variables, the string you want, and the value for defense you want to get out of it.

Re: Char and int concatenation?

PostPosted: Mon May 20, 2013 8:33 pm
by Lacotemale
item100.defense is an int declared inside a struct.

I can set defense like this:

Code: Select all
if(selectedItem==100)
{
  defense = item100.defense; //the defense is now 3 because item100.defense equals 3
}


Does that clear it up?

So, I want to have something like this instead:

void setDefense(selectedItem)
{
defense = item(selectedItem).defense;
}


This way I can avoid all the if statements of my old method. :)

Re: Char and int concatenation?

PostPosted: Mon May 20, 2013 8:38 pm
by skydereign
You can't do that with a string in C. You would need to clean up how you deal with items though. If you declare an array of items, instead of each one one by one, you could just use the following.
Code: Select all
defense = items[100].defense;

Re: Char and int concatenation?

PostPosted: Mon May 20, 2013 8:55 pm
by Lacotemale
Ah yes, I already have an array setup with structs but of course I didn't think of using that array directly. xD

*deskpalm*

Well, thanks for getting me on the right track! :)

I reduced a rather large script to one line of code. Much better!