此示例使用整数,运算符和另一个整数读取行.例如,
// 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.
的basic_ios类(这是两者的基础istream和ostream)具有转换操作员void*,其可以被隐式转换为bool.这就是它的工作原理.