这个例子读取带有整数、运算符和另一个整数的行。例如:
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
。
basic_ios
,含有这个运算符。它根据流的!fail()
评估结果返回非零值(真)。 - Bo Perssonios_base
,从中继承了basic_ios
。让我检查一下标准。 - Xeooperator bool()
有一个explicit
重载(另请参见 此问题)。 - Björn Pollexbasic_ios
来提供转换运算符。正在编辑。 - Xeo