当我们需要将字符串与来自多个变量类型的数据连接起来时,我们通常会执行以下操作:
int year = 2013;
float amount = 385.5;
stringstream concat;
string strng;
concat << "I am in the year " << year << " and I don't have in my pocket but the amount " << amount;
strng = concat.str();
cout << strng << endl;
正如我们在该代码中看到的,我们连接了许多类型的数据:year
是 int 类型,amount
是 float 和字符串I am in the year
是字符串类型。在其他编程语言中,您可以使用+
运算符执行相同的操作。
所以,回到问题:
还有另一种方法除了 stringstream
,以便在{{1}中输入来自多个类型变量的数据时连接字符串(char
或string
类型) }和C
语言?我希望能够用两种语言来做。
答案 0 :(得分:2)
使用stringstream当然非常方便,但不是唯一的方法。一种方法是使用sprintf(),另一种方法是通过itoa()或ftoa()等方法将所有值类型转换为字符串,并使用标准字符串连接方法strcat()将多个字符串组合在一起。
答案 1 :(得分:1)
您可以使用vsnprintf()
实现一种包装,以便打印到根据需要动态扩展的字符串中。在Linux上,C解决方案以asprintf()
的形式存在,它返回必须与free()
一起发布的内存:
char *concat;
asprintf(&concat, "I am in the year %d and I don't have in my pocket but the amount %f",
year, amount);
std::string strng(concat);
free(concat);
在C ++中,您可以实现一些更友好的用途,因为RAII可以为您处理内存管理问题:
int string_printf (std::string &str, const char *fmt, ...) {
char buf[512];
va_list ap;
va_start(ap, fmt);
int r = vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
if (r < sizeof(buf)) {
if (r > 0) str.insert(0, buf);
return r;
}
std::vector<char> bufv(r+1);
va_start(ap, fmt);
r = vsnprintf(&bufv[0], bufv.size(), fmt, ap);
va_end(ap);
if (r > 0) str.insert(0, &bufv[0]);
return r;
}
std::string strng;
string_printf(strng,
"I am in the year %d and I don't have in my pocket but the amount %f",
year, amount);