bogdan.css
bogdan.css

Reputation: 381

Concatenating integers to const char* strings

I have a few files named like so: file1, file2, file3, etc.

I have a function:

load(const char *file)

which I would call like so load(file1), load(file2), etc.

I am trying do this a bit more dynamically, based on the number of files imported.

So if I have more than 1 file do something like this:

if (NUM_OF_FILES > 1) {
    for (int i = 2; i <= NUM_OF_FILES; i++) {
        load("file" + i);
    }
}

However, this is not working.

Is there a way of doing this?

Upvotes: 2

Views: 4430

Answers (2)

Christian Hackl
Christian Hackl

Reputation: 27548

It depends on what version of C++ you are using. If it's C++11, the solution will involve std::to_string. If it's an older version of C++, you can convert an integer to a string like this:

#include <sstream>

// ...

std::ostringstream converter;
converter << i; // i is an int
std::string s(convert.str());

Now, the load function takes a const char *. Is it your own function? Then consider changing it so that it takes a std::string const& instead, and you'll be able to pass the string directly. Otherwise, this is how can pass the string's contents to it:

load(s.c_str());

Upvotes: 1

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154035

The type of a string literal like "file" is char const[N] (with a suitable N) whic happily decays into a char const* upon the first chance it gets. Although there is no addition defeined between T[N] and int, there is an addition defined between char const* and int: it adds the int to the pointer. That isn't quite what you want.

You probably want to convert the int into a suitable std::string, combine this with the string literal you got, and get a char const* from that:

load(("file" + std::to_string(i)).c_str());

Upvotes: 6

Related Questions