Can you create a string similar to std :: cout?

The following statement transfers all types of output to the console as a separate line of text

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

Can the same syntax be used to construct a string in a string variable? How it's done?

+7
source share
4 answers
 #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(); 

You can also use std::istringstream for multiple inputs and std::stringstream for input and output.

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

stringstream will save you here;

 #include <sstream> std::stringstream ss; ss << stuff << to << output; std::string s = ss.str(); 
+2
source
+2
source

Using 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; } 
+1
source

All Articles