I have a small piece of code to read user data, like below:
#include
#include
#include
#include
#incl
Once a failure occurs on a stream, the stream remains in a failed state (no reading can succeed) until you clear() the stream.
Right now, you're trying to read the bad data from the stream before you clear it, so that reading will never succeed. Furthermore, you don't provide any way to continue reading data from the stream after you've cleared out the bad data--you do the while loop, then when it exits, you clear the bad data (if any) from the stream, then return what you read.
For a case like this, you'll pretty much need to test separately from eof() on the stream, and continue reading until you reach eof()--either data is converted, or else it's ignored.
Given that you're trying to ignore bad data until the next white space, I'd use ignore
instead of reading data into a string. No real point in reading data you don't care about into a string.
#include<iostream>
#include<vector>
#include<algorithm>
#include<ios>
#include<iomanip>
using namespace std;
istream& read_dt(istream& in, vector<int>& nmbr) {
if (in) {
nmbr.clear();
int x;
for(;;) {
in >> x;
if (in.eof())
break;
if (in.fail()) {
in.clear();
in.ignore(100, ' ');
}
else
nmbr.push_back(x);
}
return in;
}
}
int main() {
vector<int> data;
cout << "Enter all the data: " << endl;
read_dt(cin, data);
cout << "Size: " << data.size() << endl;
}