你能以类似于std :: cout的方式创建一个字符串吗?

时间:2011-11-07 21:24:22

标签: c++

以下语句将所有类型的输出作为单个文本字符串

传递给控制台
std::cout << "Hi, my name is " << name_as_string << " and I am " << age_as_int << " years old, while weighing " << weight_as_double << " kilograms.";

我们可以使用相同的语法在字符串变量中构建字符串吗?怎么做?

4 个答案:

答案 0 :(得分:10)

#include <sstream>

std::ostringstream ss;
ss << "Hi, my name is " << name_as_string;
ss << " and I am " << age_as_int << " years old, while weighing ";
ss << weight_as_double << " kilograms.";

std::string str = ss.str();

您还可以将std::istringstream用于多个输入,并将std::stringstream用于输入和输出。

std::string str = "1 2 3 4 5";
std::istringstream ss(str);
int i;
while( ss >> i) {
    std::cout << i;
}

答案 1 :(得分:2)

stringstream会在这里救你;

#include <sstream>

std::stringstream ss;

ss << stuff << to << output;

std::string s = ss.str();

答案 2 :(得分:2)

答案 3 :(得分:1)

使用std::stringstream

#include <sstream>
#include <iostream>

int main()
{
  std::stringstream ss;
  ss << "Hi, my name is " << name_as_string << " and I am " << age_as_int << " years old, while weighing " << weight_as_double << " kilograms.";
  std::cout<<ss.str()<<std::endl;
}