I have a small piece of code to read user data, like below:
#include<iostream>
#include<vector>
#include<algorithm>
#include<ios>
#include<iomanip>
#include<string>
using namespace std;
istream& read_dt(istream& in, vector<int>& nmbr) {
if(in) {
nmbr.clear();
int x;
while(in >> x) {
nmbr.push_back(x);
}
if(in.fail()) {
string s;
in >> s;
in.clear();
}
}
return in;
}
int main() {
vector<int> data;
cout << "Enter all the data: " << endl;
read_dt(cin, data);
cout << "Size: " << data.size() << endl;
}
When I compile and execute this above program using the following data: 1 2 3 4 r t 5 6 7
I seem to get a vector of size 4 instead of size 7. What I though, I implemented above is, that when a user gives invalid inputs as data (in this case 'r' and 't'), that data is discarded and the input is cleared (using in.clear()), and the remaining inputs are "pushed" into the vector data.
But that does not seem to be happening. What am I doing wrong? Can someone please help?
Thanks.