int i = 4;
string text = "Player ";
cout << (text + i);
Run Code Online (Sandbox Code Playgroud)
我想要它打印Player 4.
上面显然是错误的,但它显示了我在这里要做的事情.有没有一种简单的方法可以做到这一点,还是我必须开始添加新的包含?
hea*_*der 236
使用C++ 11,您可以编写:
#include <string> // to use std::string, std::to_string() and "+" operator acting on strings
int i = 4;
std::string text = "Player ";
text += std::to_string(i);
Run Code Online (Sandbox Code Playgroud)
Seb*_*edl 192
好吧,如果你使用cout,你可以直接写整数,就像在
std::cout << text << i;
Run Code Online (Sandbox Code Playgroud)
将各种对象转换为字符串的C++方法是通过字符串流.如果你没有一个方便,只需创建一个.
#include <sstream>
std::ostringstream oss;
oss << text << i;
std::cout << oss.str();
Run Code Online (Sandbox Code Playgroud)
或者,您可以只转换整数并将其附加到字符串.
oss << i;
text += oss.str();
Run Code Online (Sandbox Code Playgroud)
最后,Boost库提供了boost::lexical_cast一个包含字符串流转换的语法,类似于内置类型转换.
#include <boost/lexical_cast.hpp>
text += boost::lexical_cast<std::string>(i);
Run Code Online (Sandbox Code Playgroud)
这也是相反的方式,即解析字符串.
Eri*_*ric 115
printf("Player %d", i);
Run Code Online (Sandbox Code Playgroud)
(你喜欢我的答案;我仍然讨厌C++ I/O运算符.)
:-P
Fir*_*cer 19
这些适用于一般字符串(如果您不想输出到文件/控制台,但存储以供以后使用或某些东西).
boost.lexical_cast
MyStr += boost::lexical_cast<std::string>(MyInt);
Run Code Online (Sandbox Code Playgroud)
字符串流
//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();
// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;
Run Code Online (Sandbox Code Playgroud)
您的示例似乎表明您希望显示一个字符串后跟一个整数,在这种情况下:
string text = "Player: ";
int i = 4;
cout << text << i << endl;
Run Code Online (Sandbox Code Playgroud)
会工作得很好。
但是,如果您要存储字符串位置或传递它,并且经常执行此操作,则重载加法运算符可能会受益。我在下面演示了这一点:
#include <sstream>
#include <iostream>
using namespace std;
std::string operator+(std::string const &a, int b) {
std::ostringstream oss;
oss << a << b;
return oss.str();
}
int main() {
int i = 4;
string text = "Player: ";
cout << (text + i) << endl;
}
Run Code Online (Sandbox Code Playgroud)
事实上,您可以使用模板来使这种方法更强大:
template <class T>
std::string operator+(std::string const &a, const T &b){
std::ostringstream oss;
oss << a << b;
return oss.str();
}
Run Code Online (Sandbox Code Playgroud)
现在,只要对象b具有定义的流输出,您就可以将其附加到字符串(或者至少是其副本)。