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

The following statement pipes all sorts of output to the console as a single string 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 we use this same syntax to build a string in a string variable? How is it done?

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 input, and std::stringstream for both input and output.

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

Need Your Help

How can I delete objects from memory in JavaScript?

javascript memory garbage-collection easeljs box2dweb

I am using EaselJS and Box2DWeb to create an arrow shooting game. Every time an arrow collides with another body, it dies, and I call this function:

How to redirect to back after signing completion in docuSign

javascript node.js docusignapi docusign electronic-signature

I'm trying to embedded signing workflow through this API http://iodocs.docusign.com/APIWalkthrough/embeddedSigning

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.