Milk
Milk

Reputation: 657

Create const char* using ints

whats the best way of creating a 'const char*' using available variables? For example, a function requires a const char* as a parameter to locate a file i.e. "invader1.png". If I have 5 different invader images, how can I iterate from 1:5 so "Invader1.png".."Invader2.png..etc etc so i want "invader" + %d + ".png"

i tried sprintf and casting but to no avail.

I hope my description makes sense, thanks

update with code:

 for (int y=0; y<250; y+=50){
            stringstream ss;
            ss << "invader" << (y/50) << ".png";
            const char* rr = ss.str().c_str();
            printf("%s", rr);
            for (int x=0; x<550;x+=50){
                Invader inv(rr, x+50, y+550, 15, 15, 1, false, (y/50 + 50));
                invaders[i] = inv;
                i++;
            }
        }

Upvotes: 2

Views: 1162

Answers (3)

reko_t
reko_t

Reputation: 56430

Since you're using C++, you can simply use std::string and then use the c_str() function to get a const char* which you can pass to the function. One simple way to construct such strings is to use std::ostringstream from <sstream>:

for (int i = 1; i <= 5; ++i) {
    std::ostringstream ss;
    ss << "invader" << i << ".png";
    foo(ss.str().c_str()); // where foo is the specified function
}

You could also use sprintf() and a character array, but then you need to pay attention to things like the size of the buffer. For the sake of completeness, here's how to do the same with sprintf, but I suggest you go with the std::string approach, which is more C++-like:

for (int i = 1; i <= 5; ++i) {
    char buf[13]; // big enough to hold the wanted string
    std::ostringstream ss;
    sprintf(buf, "invader%d.png", i);
    foo(buf); // where foo is the specified function
}

Upvotes: 1

Pubby
Pubby

Reputation: 53047

Use std::stringstream. Something like this:

std::stringstream ss;
ss << "invader" << my_int << ".png";
my_func(ss.str().c_str());

Upvotes: 3

ehanoc
ehanoc

Reputation: 2217

Then i would guess your looking to cast an int variable to char, so you can iterate through your invader%d.png files.

Have you tried itoa function ?

http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

Upvotes: 0

Related Questions