How does the istringstream >> return value operator work?

This example reads lines with an integer, an operator, and another integer. For instance,

25 * 3

4/2

// 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) ?

I think the test is always true because instream!=NULL .

+6
source share
2 answers

The basic_ios class (which is the base of both istream and ostream ) has a conversion operator to void* , which can be implicitly converted to bool . How it works.

+7
source

Source: https://habr.com/ru/post/891517/


All Articles