我有一些整数,让我们说one two和three.我想创建一个字符串,如
char* example = "There are " + one + " bottles of water on " +
two + " shelves in room number " + three + "\n".`
Run Code Online (Sandbox Code Playgroud)
这在C/C++中不起作用.如何将这种类型的值存储在char*中?
在C中,有多种方法可以实现,具体取决于您希望如何分配内存[*].对于从堆中分配它的直接选项:
len = snprintf(0, 0, "%d bottles, %d shelves, room %d\n", one, two, three);
char *result = malloc(len+1);
if (result == 0) { /* handle error */ }
snprintf(result, len+1, "%d bottles, %d shelves, room %d\n", one, two, three);
/* some time later */
free(result);
Run Code Online (Sandbox Code Playgroud)
注意非标准实现snprintf,超出缓冲区时不返回长度.检查您的文档.
在C++中,snprintf不在标准中,即使它可用,上面的代码也需要转换malloc [**]的结果.C++添加了使用stringstreams的选项:
std::stringsteam r;
r << one << " bottles, " << two << " shelves, room " << three << "\n";
std::string result = r.str();
// if you absolutely need a char*, use result.c_str(), but don't forget that
// the pointer becomes invalid when the string, "result" ceases to exist.
Run Code Online (Sandbox Code Playgroud)
这样可以减少缓冲区长度的混乱,使资源管理更容易,并避免printf与朋友一起为格式说明符传递错误类型的参数的风险.这通常是首选方案.
然而,在某些情况下它的灵活性较低:格式硬连接到代码中而不是包含在格式字符串中,因此使文本可配置更加困难.它也可能有点难以阅读,例如,在任何此类代码行的第一个版本上省略空格字符并不罕见.但是如果你想snprintf在C++中使用这个方法,并且snprintf在你的实现中可用,那么你可以利用C++更容易的内存管理,如下所示:
len = std::snprintf(0, 0, "%d bottles, %d shelves, room %d\n", one, two, three);
std::vector<char> r(len+1);
std::snprintf(&r[0], r.size(), "%d bottles, %d shelves, room %d\n", one, two, three);
char *result = &r[0];
// again, "result" is only valid as long as "r" is in scope
Run Code Online (Sandbox Code Playgroud)
[*]请注意,您不能在a中"存储"字符串char*,因为a char*只是一个指针.您可以在a中存储指向字符串的指针char*,但字符串本身是完全独立的.
[**]因为C和C++是不同的语言!
C++不是VB.但是你有很多选择.
#include <sstream>
#include <string>
stringstream ss;
ss<< "There are " << one << " bottles of water on " << two << " shelves in room number " << three;
string s = ss.str();
Run Code Online (Sandbox Code Playgroud)
#include <boost/format.hpp>
#include <string>
string s = (boost::format("There are %1% bottles on %2% shelves in room number %3%")%one%two%three).str();
Run Code Online (Sandbox Code Playgroud)
char buffer[1024] = {};
sprintf(buffer, "There are %d bottles on %d shelves in room number %d", one, two, three);
Run Code Online (Sandbox Code Playgroud)