我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
当前回答
如果你使用MFC,你可以使用CString
CString nameAge = "";
nameAge.Format("%s%d", "John", 21);
托管c++也有一个 字符串格式化程序。
其他回答
常见答案:itoa()
这很糟糕。正如这里指出的,Itoa是非标准的。
如果有Boost,可以使用Boost::lexical_cast<std::string>(age)将整数转换为字符串。
另一种方法是使用stringstreams:
std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
第三种方法是使用C库中的sprintf或snprintf。
char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;
其他海报建议使用itoa。这不是一个标准函数,所以如果你使用它,你的代码将不能移植。有些编译器不支持它。
在我看来,最简单的答案是使用sprintf函数:
sprintf(outString,"%s%d",name,age);
#include <iostream>
#include <sstream>
std::ostringstream o;
o << name << age;
std::cout << o.str();
这是最简单的方法:
string s = name + std::to_string(age);