6

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

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

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

kev
  • 155,172
  • 47
  • 273
  • 272

2 Answers2

7

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.

Xeo
  • 129,499
  • 52
  • 291
  • 397
  • 3
    I think it is the other base class, confusingly named `basic_ios`, that has this operator. It returns non-zero (true) based on evaluating `!fail()` for the stream. – Bo Persson Jun 28 '11 at 06:57
  • @Bo: Atleast on MSVC it's `ios_base`, from which `basic_ios` inherits. Lemme check the standard. – Xeo Jun 28 '11 at 07:36
  • 1
    I believe this can be thought of as an implementation of the [Safe bool idiom](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool). Note that in C++0x, there is an `explicit` overload for `operator bool()` instead (see also [this question](http://stackoverflow.com/questions/6242768/)). – Björn Pollex Jun 28 '11 at 07:41
  • @Bo: You were right, the standard defines `basic_ios` to provide the conversion operator. Editing. – Xeo Jun 28 '11 at 07:47