Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the "string", "stream" and "stringstream" classes in C++?

Tags:

c++

stl

I want to know what's the difference between string and stream in c++, and what's stringstream?

like image 632
user40040 Avatar asked Nov 23 '08 07:11

user40040


2 Answers

  • istream and ostream: interfaces to streaming data (files, sockets, etc.)
  • istringstream: an istream that wraps a string and offers its contents
  • ostringstream: an ostream that saves the content written to it as a string

Example:

istringstream datastream("1 2 3");

int val;
datastream >> val;
cout << val << endl; // prints 1

datastream >> val;
cout << val << endl; // prints 2

datastream >> val;
cout << val << endl; // prints 3


ostringstream outstream;
outstream << 1 << "+" << 2 << "=" << 3;
cout << outstream.str() << endl; // prints "1+2=3"
like image 131
orip Avatar answered Sep 20 '22 19:09

orip


Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.

like image 28
Ari Ronen Avatar answered Sep 21 '22 19:09

Ari Ronen