int i = 4;
string text = "Player ";
cout << (text + i);

我想打印参与人4。

上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?


当前回答

另一种可能是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;
}

其他回答

这些适用于一般字符串(以防你不想输出到文件/控制台,而是存储以供以后使用)。

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;

这里有一个小的转换/附加示例,其中有一些我以前需要的代码。

#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

请注意,在最后两行中,您在实际打印出修改后的字符串之前保存了它,如果需要,您可以稍后使用它。

如果使用Windows/MFC,并且需要字符串的即时输出,请尝试:

int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);
cout << text << i;

有几个选项,您想要哪个取决于上下文。

最简单的方法是

std::cout << text << i;

或者你想把它写在一条直线上

std::cout << text << i << endl;

如果你正在编写一个单线程程序,如果你不经常调用这段代码(这里的“很多”是每秒数千次),那么你就完成了。

如果您正在编写一个多线程程序,并且有多个线程正在向cout写入内容,那么这段简单的代码可能会给您带来麻烦。让我们假设编译器附带的库使cout线程足够安全,任何对它的单独调用都不会被中断。现在让我们假设一个线程正在使用这段代码编写“参与人1”,另一个线程正在编写“参与人2”。如果你幸运的话,你会得到以下信息:

Player 1
Player 2

如果你运气不好,你可能会得到如下的结果

Player Player 2
1

问题是std::cout << text << i << endl;变成3个函数调用。代码等价于以下内容:

std::cout << text;
std::cout << i;
std::cout << endl;

如果你使用c风格的printf,并且你的编译器再次提供了一个具有合理线程安全性的运行时库(每个函数调用都是原子的),那么下面的代码会更好地工作:

printf("Player %d\n", i);

能够在单个函数调用中执行某些操作,使得io库能够在幕后提供同步,现在您的整行文本都将被原子地写入。

对于简单的程序,std::cout非常好。再加上多线程或其他复杂程序,不那么时尚的printf看起来就更有吸引力了。