istringstream operator>> 返回值如何工作?

6

这个例子读取带有整数、运算符和另一个整数的行。例如:

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个回答

7

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


3
我认为有另一个基类,它被混淆地命名为basic_ios,含有这个运算符。它根据流的!fail()评估结果返回非零值(真)。 - Bo Persson
@Bo:至少在MSVC上,它是ios_base,从中继承了basic_ios。让我检查一下标准。 - Xeo
1
我认为这可以被视为实现 安全 bool 习惯用法。请注意,在 C++0x 中,operator bool() 有一个 explicit 重载(另请参见 此问题)。 - Björn Pollex
@Bo:你是对的,标准定义了basic_ios来提供转换运算符。正在编辑。 - Xeo


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接