How to keep reading after while loop?

4052 views c++
5

I have a .txt file that has a sequence of numbers and spaces on the first line that I wish to read into a vector. Then there is a '$' symbol on the next line. On the line after that is another line containing a sequence of numbers and spaces (like the first) that I'd like to read into another vector. For example

1 2 3 4 5
$
4 3 2 1 6

I've tried everything but can't keep reading after the initial while loop reads in integers. How do I move past the second line and read the third? Right now It just outputs the first line. Currently, this is my code:

int main(int argc, const char * argv[]) {
    ifstream file(argv[1]); 
    if (file.is_open() && file.good()){
        int addMe;
        vector<int> addMeList;
        while(file>>addMe){
            cout <<addMe<<endl;
            addMeList.push_back(addMe);
        }

        string skip;
        while(file >> skip)
            cout << skip << endl;

        int searchQuery;
        vector<int> searchQueries;

        while(file>>searchQuery){
            searchQueries.push_back(searchQuery);
        }

        for (int i=0; i<searchQueries.size();i++)
        {
            cout << searchQueries[i]<<endl;
        }
    }
    return 0;

}

answered question

1 Answer

7

Two problems:

  1. The first loop will cause the streams failbit to be set (when it attempts to read the '$' from the second line). If that bit is set, you can't read more from the stream. You need to clear the stream state.

  2. Once you've done the above, the second loop will read the rest of the file.

One possible solution is to read lines instead. Use e.g. std::getline to read a line. Put the line into a std::istringstream, and read the values from that.

posted this

Have an answer?

JD

Please login first before posting an answer.