What exactly does stringstream do?

user3104350 picture user3104350 · Dec 15, 2013 · Viewed 256.6k times · Source

I am trying to learn C++ since yesterday and I am using this document:http://www.cplusplus.com/files/tutorial.pdf (page 32) . I found a code in the document and I ran it. I tried inputting Rs 5.5 for price and an integer for quantity and the output was 0. I tried inputting 5.5 and 6 and the output was correct.

// stringstreams
#include <iostream> 
#include <string> 
#include <sstream> 

using namespace std; 

int main () 
{ 
  string mystr; 
  float price = 0; 
  int quantity = 0; 

  cout << "Enter price: "; 
  getline (cin,mystr); 
  stringstream(mystr) >> price; 
  cout << "Enter quantity: "; 
  getline (cin,mystr); 
  stringstream(mystr) >> quantity; 
  cout << "Total price: " << price*quantity << endl; 
  return 0; 
}

Question: What exactly does the mystring command do? Quoting from the document:

"In this example, we acquire numeric values from the standard input indirectly. Instead of extracting numeric values directly from the standard input, we get lines from the standard input (cin) into a string object (mystr), and then we extract the integer values from this string into a variable of type int (quantity)."

My impression was that the function will take the integral part of a string and use that as input.

(I don't exactly know how to ask a question here. I am also new to programming) Thank you.

Answer

richard.g picture richard.g · Dec 15, 2013

Sometimes it is very convenient to use stringstream to convert between strings and other numerical types. The usage of stringstream is similar to the usage of iostream, so it is not a burden to learn.

Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without a real I/O channel.

The basic member functions of stringstream class are

  • str(), which returns the contents of its buffer in string type.

  • str(string), which set the contents of the buffer to the string argument.

Here is an example of how to use string streams.

ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;

The result is dec: 15 hex: f.

istringstream is of more or less the same usage.

To summarize, stringstream is a convenient way to manipulate strings like an independent I/O device.

FYI, the inheritance relationships between the classes are:

string stream classes