以下语句将所有类型的输出作为单个文本字符串
传递给控制台std::cout << "Hi, my name is " << name_as_string << " and I am " << age_as_int << " years old, while weighing " << weight_as_double << " kilograms.";
我们可以使用相同的语法在字符串变量中构建字符串吗?怎么做?
答案 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;
}