The C++ std::istream::operator>>() function is an extraction operator used to read the formatted data from a stringstream object into variables. It works similar to the >> operator with std::cin, but instead, it extracts data from a string buffer.
This function has 3 polymorphic variants: with using the arithmetic type or stream buffers or manipulators (you can find the syntaxes of all the variants below).
SyntaxFollowing is the syntax for std::istream::operator>>() function.
istream& operator>> (bool& val); istream& operator>> (short& val); istream& operator>> (unsigned short& val); istream& operator>> (int& val); istream& operator>> (unsigned int& val); istream& operator>> (long& val); istream& operator>> (unsigned long& val); istream& operator>> (long long& val); istream& operator>> (unsigned long long& val); istream& operator>> (float& val); istream& operator>> (double& val); istream& operator>> (long double& val); istream& operator>> (void*& val); or istream& operator>> (streambuf* sb ); or istream& operator>> (istream& (*pf)(istream&)); istream& operator>> (ios& (*pf)(ios&)); istream& operator>> (ios_base& (*pf)(ios_base&));Parameters
This function returns the basic_istream object (*this).
ExceptionsIf an exception is thrown, the object is in a valid state.
Data racesModifies val or the object pointed by sb.
ExampleLet's look at the following example, where we are going to read the single integer.
#include <iostream> #include <sstream> #include <string> int main() { std::string a = "11"; std::stringstream b(a); int x; b >> x; std::cout << "Result : " << x << std::endl; return 0; }Output
Output of the above code is as follows −
Result : 11Example
Consider the following example, where we are going to read multiple data types.
#include <iostream> #include <sstream> #include <string> int main() { std::string a = "11 2.3 TutorialsPoint"; std::stringstream b(a); int x; float y; std::string z; b >> x >> y >> z; std::cout << "x : " << x << ", y : " << y << ", z : " << z << std::endl; return 0; }Output
Following is the output of the above code −
x : 11, y : 2.3, z : TutorialsPointExample
In the following example, we are going to read the list if integers.
#include <iostream> #include <sstream> #include <string> #include <vector> int main() { std::string x = "1 2 3 4 5"; std::stringstream y(x); std::vector<int> a; int b; while (y >> b) { a.push_back(b); } std::cout << "Result :"; for (int n : a) { std::cout << " " << n; } std::cout << std::endl; return 0; }Output
If we run the above code it will generate the following output −
Result : 1 2 3 4 5
istream.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4