Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
908 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...