I want to know what's the difference between string and stream in c++, and what's stringstream?
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.
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.
istream
andostream
: interfaces to streaming data (files, sockets, etc.)istringstream
: anistream
that wraps a string and offers its contentsostringstream
: anostream
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"
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.