开发者

how does istringstream operator>> return value work?

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();开发者_JAVA百科     // 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.


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.


"[15.4] How does that funky while (std::cin >> foo) syntax work?"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜