This example reads lines with an integer, an operator, and another integer. For example,
// sstream-line-input.cpp - Example of input string stream.
// This accepts only lines with an int, a char, and an int.
// Fred Swartz 11 Aug 2003
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//================================================================ main
int main() {
string s; // Where to store each line.
int a, b; // Somewhere to put the ints.
char op; // Where to save the char (an operator)
istringstream instream; // Declare an input string stream
while (getline(cin, s)) { // Reads line into s
instream.clear(); // Reset from possible previous errors.
instream.str(s); // Use s as source of input.
if (instream >> a >> op >> b) {
instream >> ws; // Skip white space, if any.
if (instream.eof()) { // true if we're at end of string.
cout << "OK." << endl;
} else {
cout << "BAD. Too much on the line." << endl;
}
} else {
cout << "BAD: Didn't find the three items." << endl;
}
}
return 0;
}
operator>>
Return the object itself (*this).
How does the test if (instream >> a >> op >> b)
work?
I think the test always true
, because instream!=NULL
.
This operator ( >> ) applied to an input stream is known as extraction operator. It is overloaded as a member function for: (1) arithmetic types. Extracts and parses characters sequentially from the stream to interpret them as the representation of a value of the proper type, which is stored as the value of val .
The std::istringstream is a string class object which is used to stream the string into different variables and similarly files can be stream into strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed as a string object.
The basic_ios
class (which is a base of both istream
and ostream
) has a conversion operator to void*
, which can be implicitly converted to bool
. That's how it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With