Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...