简体   繁体   English

将整数连接到const char *字符串

[英]Concatenating integers to const char* strings

I have a few files named like so: file1 , file2 , file3 , etc. 我有几个这样命名的文件: file1file2file3等。

I have a function: 我有一个功能:

load(const char *file)

which I would call like so load(file1) , load(file2) , etc. 我会这样称呼load(file1)load(file2)等。

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? 有办法吗?

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. 字符串文字(如"file" )的类型为char const[N] (具有合适的N ),它在第一次获得机会时会愉快地衰减为char const* 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. 尽管在T[N]int之间没有伪造的加法,但是在char const*int之间定义了一个加法:它将int加到指针。 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: 您可能希望将int转换为合适的std::string ,将其与您获得的字符串文字结合起来,并从中获得char const*

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

It depends on what version of C++ you are using. 这取决于您使用的C ++版本。 If it's C++11, the solution will involve std::to_string . 如果是C ++ 11,则解决方案将涉及std::to_string If it's an older version of C++, you can convert an integer to a string like this: 如果它是C ++的旧版本,则可以将整数转换为这样的字符串:

#include <sstream>

// ...

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

Now, the load function takes a const char * . 现在, load函数采用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. 然后考虑对其进行更改,以使其改为使用std::string const& ,您将可以直接传递该字符串。 Otherwise, this is how can pass the string's contents to it: 否则,这是将字符串的内容传递给它的方法:

load(s.c_str());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM