istringstream运算符怎么样>>回报价值吗?

时间:2011-06-28 06:25:20

标签: c++

此示例使用整数,运算符和另一个整数读取行。例如,

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>>返回对象本身(* this)。

测试if (instream >> a >> op >> b)如何运作?

我认为测试总是true,因为instream!=NULL

2 个答案:

答案 0 :(得分:7)

basic_ios类(istreamostream的基础)都有void*转换运算符,可以隐式转换为bool }。这就是它的工作原理。

答案 1 :(得分:0)