add each line from a text file into a vector

ok so basically i have a .txt file which is formatted like this
1
2
3
4
5
thing1
thing2
thing3
thing4
etc.

and i have a vector. i want to take every line of that text file and put it into that vector . how can i do that?

i tried this, but it didn't seem to work properly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    ifstream infile("exclusions.txt");
    if (infile.good())
    {
        string sLine;

        while (!infile.eof())
        {
            infile >> sLine;
            exclusionlist.push_back(sLine.data());

        }

        infile.close();
            
    }
Line 6: Do not loop on (! stream.eof()) or (stream.good()). This does not work the way you expect. The eof bit is set true only after you make a read attempt on the file. This means after you read the last record of the file, eof is still false. Your attempt to read past the last record sets eof, but you're not checking it there. You proceed as if you had read a good record. This will result in reading an extra (bad) record. The correct way to deal with this is to put the >> (or getline) operation as the condition in the while statement.
1
2
3
  while (stream >> var) // or while (getline(stream,var))
  {  //  Good operation
  }


You haven't shown the declaration of exclusionlist.
I'm guessing that you've declared it as:
std::vector<const char *> exclusonlist;
sLine only occurs once at line 4. The data in sLine is wiped out each time you do a >> operation at line 8. Line 9 saves a copy of a const char * pointer, not the data.
Declare your vector as:
std::vector<std::string> exclusionlist;
Then simply push_back(sLine).
Last edited on
Topic archived. No new replies allowed.