向字符串中添加变量和文本

Adding variables and text to a string?

本文关键字:文本 变量 添加 字符串      更新时间:2023-10-16

有没有办法让字符串抓取一组文本和一个变量?类似这样的东西:

std::string morning = "morning";
std::string str = "Good " [insert morning here] ", user!";

很明显,我想做一些比我刚才举的例子更复杂的事情,但我相信你能理解我想做什么

提前谢谢,伙计们!

您只需使用std::string::operator+,类似于:

std::string str = "Good " + morning + ", user!";

另一种方法是使用std::ostringstream:

std::string morning = "morning";
unsigned int user_id = 384;
std::ostringstream out_stream;
out_stream << "Good " << morning << ", user #" << user_id;
std::string str = out_stream.str();

不幸的是,ostream和operator+都不起作用。我最后使用了一些字符和push_back的东西。不管怎样,谢谢大家!