int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
当前回答
cout << text << i;
ostream的<<操作符返回ostream的引用,因此可以继续链接<<操作。也就是说,以上基本等同于:
cout << text;
cout << i;
其他回答
printf("Player %d", i);
(你可以给我的答案投票;我仍然讨厌c++的I/O操作符。)
:-P
cout << text << " " << i << endl;
这里的一种方法是直接打印输出,如果你的问题需要它。
cout << text << i;
否则,最安全的方法之一就是使用
sprintf(count, "%d", i);
然后复制它到你的“文本”字符串。
for(k = 0; *(count + k); k++)
{
text += count[k];
}
这样,您就有了所需的输出字符串
有关sprintf的更多信息,请参见: http://www.cplusplus.com/reference/cstdio/sprintf
这里有一个小的转换/附加示例,其中有一些我以前需要的代码。
#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
请注意,在最后两行中,您在实际打印出修改后的字符串之前保存了它,如果需要,您可以稍后使用它。
这些适用于一般字符串(以防你不想输出到文件/控制台,而是存储以供以后使用)。
boost.lexical_cast
MyStr += boost::lexical_cast<std::string>(MyInt);
字符串流
//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;