John
John

Reputation: 105

How to insert an integer inside a string?

How do I insert an integer i into a string? I tried this, but it doesn't work:

for (int i = 0; i < maxFrameBoss1; i++) {
    boss1Image[i] = al_load_bitmap("boss1//frame_0" + i + "_delay-0.03s.png");
}

Upvotes: 1

Views: 721

Answers (4)

user9212993
user9212993

Reputation:

The easy way to construct strings from arbitrary input types is to use std::ostringstream like so:

for (int i = 0; i < maxFrameBoss1; i++) {
    std::ostringstream bitmap_filename_builder;
    bitmap_filename_builder << "boss1//frame_0" << i << "_delay-0.03s.png";
    boss1Image[i] = al_load_bitmap(bitmap_filename_builder.str().c_str());
}

When using this, take care about the lifetime of the temporarily created std::string variable returned by the std::ostrinsgstream::str() function. The result of the c_str() function may become a dangling pointer after execution of that statement. Be sure that the function you're calling takes a copy of that c-style string parameter, or just uses it in a strongly sequential manner and doesn't store that pointer as a state elsewhere.

Upvotes: 4

Justin
Justin

Reputation: 25287

The easiest solution is to just use std::to_string(i), but that could potentially lead to extra allocations, as std::string cannot know the final size in the intermediate + operations.

Instead, you may want to use absl::StrCat or some other variant:

for (int i = 0; i < maxFrameBoss1; i++) {
    std::string filename = absl::StrCat("boss1//frame_0", i, "_delay-0.03s.png");
    boss1Image[i] = al_load_bitmap(filename.c_str());
}

This is a relatively small performance point, but the solution is easy enough to be worth mentioning.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206567

How do I insert an "i" variable into a string.

There is a standard library function to convert an int to a std::string. See http://en.cppreference.com/w/cpp/string/basic_string/to_string.

Use

std::string filename = std::string("boss1//frame_0") + std::to_string(i) + "_delay-0.03s.png";
boss1Image[i] = al_load_bitmap(filename);

If al_load_bitmap cannot use a std::string, use:

std::string filename = std::string("boss1//frame_0") + std::to_string(i) + "_delay-0.03s.png";
boss1Image[i] = al_load_bitmap(filename.c_str());

Upvotes: 4

Jerry Coffin
Jerry Coffin

Reputation: 490098

You need to convert i to a string first. Then concatenate the strings. Finally (apparently) get a pointer to char for your al_load_bitmap:

for (int i = 0; i < maxFrameBoss1; i++) {
    std::string filename = "boss1//frame_0" + std::to_string(i) + "_delay-0.03s.png";
    boss1Image[i] = al_load_bitmap(filename.c_str());
}

Upvotes: 5

Related Questions