Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does istringstream operator>> return value work?

Tags:

c++

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.

like image 716
kev Avatar asked Jun 28 '11 06:06

kev


People also ask

What is the >> operator C++?

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 .

What does Istringstream mean in C++?

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.


1 Answers

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.

like image 160
Xeo Avatar answered Oct 16 '22 10:10

Xeo