4

I have to read a file that contains a list of paths which are stored in a vector.

    vector<string> files;
    ifstream in;
    string x;

    while( !in.eof() ) {
       in >> x;
       files.push_back(x);
    }

but the problem is that when the last path is read in.eof() is still false and the loop continue for another unwanted step. A fix could be a thing like this

    vector<string> files;
    ifstream in;
    string x;

    while( in >> x ) {
       files.push_back(x);
    }

but I think that isn't a great solution in the case of a more complex code in the while loop. Am I wrong?

bluePhlavio
  • 537
  • 5
  • 18

1 Answers1

2

This will allow you to read to the end of the file and no further. As long as the file has text in it, this will read each line.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
 string line;
 ifstream myfile ("example.txt");
 if (myfile.is_open())
 {
   while ( getline (myfile,line) )
   {
     cout << line << '\n';
   }
   myfile.close();
 }

 else cout << "Unable to open file"; 

 return 0;
}
David G
  • 94,763
  • 41
  • 167
  • 253
McCormick32
  • 185
  • 11