Search code examples
cstringsdlchars

How to add a value to a string?


I am using C and the SDL library and am trying to express something like the following code:

Surface = SDL_LoadBMP("Resources/Images/ButtonPlay.bmp");

as something like this:

ButtonName = "ButtonPlay";
Surface = SDL_LoadBMP("Resources/Images/"+ButtonName+".bmp");

to introduce some type of templating.

I have tried various codes (including some from similar questions) and cannot get it to work.

I just want a quick and easy way to do it, preferably without any additional library.


Solution

  • You could use the strcat function (http://linux.die.net/man/3/strcat)

    It allows you to join two string by appending the src arg to the dest arg.

    ButtonName = "ButtonPlay";
    res = strcat("Resources/Images/", ButtonName);
    res = strcat(res, ".bmp");
    Surface = SDL_LoadBMP(res);
    

    You can find easier ways to do this but this one is clear and simple.