int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
当前回答
cout << text << " " << i << endl;
其他回答
cout << text << i;
ostream的<<操作符返回ostream的引用,因此可以继续链接<<操作。也就是说,以上基本等同于:
cout << text;
cout << i;
另一种可能是Boost。格式:
#include <boost/format.hpp>
#include <iostream>
#include <string>
int main() {
int i = 4;
std::string text = "Player";
std::cout << boost::format("%1% %2%\n") % text % i;
}
为了记录,如果您想在实际输出字符串之前创建字符串,还可以使用std::stringstream。
这里有一个小的转换/附加示例,其中有一些我以前需要的代码。
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}
输出将是:
/dev/video
/dev/video456
/dev/video321
/dev/video123
请注意,在最后两行中,您在实际打印出修改后的字符串之前保存了它,如果需要,您可以稍后使用它。
使用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);