istream reading after failure

前端 未结 1 1092
孤独总比滥情好
孤独总比滥情好 2021-01-29 02:35

I have a small piece of code to read user data, like below:

#include
#include
#include
#include
#incl         


        
相关标签:
1条回答
  • 2021-01-29 03:11

    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;
    }
    
    0 讨论(0)
提交回复
热议问题