如何在c++中向字符串中添加多个项目

How to add multiple items to string in c++?

本文关键字:添加 项目 字符串 c++      更新时间:2023-10-16

我知道怎么用cout:

cout << "string" << 'c' << 33;

但是如何执行此操作以便将输出重定向到变量而不是直接到标准输出?

const char* string << "string" << 'c' << 33; //doesn't work

使用c++标准库中的std::stringstream

它的工作原理如下:

std::stringstream ss;
ss << "string" << 'c' << 33;
std::string str = ss.str();
const char* str_ansi_c = str.c_str();

请记住,当您使用c样式的str_ansi_c时,str仍然需要在作用域中

#include <sstream>
#include <iostream>
main()
{
  std::stringstream ss;
  ss << "string" << 'c' << 33;
  std::string str = ss.str();
  std::cout << str;
}