istringstream运算符>>返回值如何工作?

kev*_*kev 6 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;
}
Run Code Online (Sandbox Code Playgroud)

operator>>返回对象本身(*this).

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

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

Xeo*_*Xeo 7

basic_ios类(这是两者的基础istreamostream)具有转换操作员void*,其可以被隐式转换为bool.这就是它的工作原理.

  • 我认为这是另一个基类,混淆地命名为`basic_ios`,它有这个运算符.它基于为流评估`!fail()`返回非零(true). (3认同)