书中示例:
int ival;
// read cin and test only for EOF; loop is executed even if there are other IO failures
while (cin >> ival, !cin.eof()) {
if (cin.bad()) // input stream is corrupted; bail out
throw runtime_error("IO stream corrupted");
if (cin.fail()) { // bad input
cerr<< "bad data, try again"; // warn the user
cin.clear(istream::failbit); // reset the stream
continue; // get next input
}
// ok to process ival
}
我在windowsxp环境下,使用vs2003的编译器编译并执行,发现陷入死循环。
利用string对象和sstream可以实现预期效果:
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <string>
#include <cctype>
using namespace std;
using std::string;
void cinTest() {
int ival;
string line;
string word;
while (getline(cin, line)) {
istringstream lstream(line);
while (lstream >> word) {
if (!isdigit(word[0])) {
cerr<< "bad data: " << word << endl;
continue;
} else {
istringstream wstream(word);
wstream >> ival;
}
} // while small
} // while large
}
int main() {
cinTest();
return 0;
}