tags:

views:

1318

answers:

4

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

+3  A: 

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.

Also... google is your friend.

argonide
Stackoverflow is supposed to be a wiki-like resource at the top of many google searches. People can ask any question if it hasn't been asked before.
fluffels
+1  A: 

My guess is that a stringstream is like an iostream, but instead of writing to or reading from a file, you write to or read from a string.

strager
+4  A: 
  • 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"
orip
A: 

In C and/or Unix, the basic metaphor was the file. Standard out, standard in, network sockets were all represented using file descriptors. Thus you can use fprintf() to write into these "files" without knowing what's really underneath.

As a safer and cooler alternative, C++ presented iostream as the basic metaphor which is almost built into the language using << operator. Again, files, strings and (with library) network can be accessed using streams without knowing what it is.

eed3si9n