-1

Given a method that I wrote on my own, a text file is given and I want to save the items into a vector<Object> referenceObject. It works nearly, but if I got in my text file objects like, for example: " Book of light ", it just saves "Book", so it stops reading on the first space.

I read some other StackOverflow questions like mine, but for my problem they don't work.

Question: It returns all objects of my text file, except for my first object. So my list starts by index=1 and not by index=0. Why?

void openfile() {
    ifstream inFile;
    inFile.open("textfile");

    if (inFile.fail()) {
        cerr << "error open this file" << endl;
        exit(1);
    }

    string item;
    int count = 0;
    vector<Object> referenceObject;

    while (!inFile.eof()) {

        while (getline(inFile, item)) {

            inFile >> item;

            Object s;
            s.setName(item);

            referenceCards.push_back(s);

            std::cout << count << ' ' << referenceObject.at(count).getName() << endl;

            count++;
        }
    }
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
du7ri
  • 5
  • 2

1 Answers1

5

When you do this:

while (getline(inFile, item)) {  // reads line into item
     inFile >> item;             // overwrites item 
     // ...                      // do stuff with item
}

You are reading the first line, and then immediately ignoring it (by overwriting it with the first string up to the space from the second line).

Instead, simply do this:

while (getline(inFile, item)) {  // read line into item
     // ...                      // do stuff with item
}

Also, avoid this check:

while (!inFile.eof()) 

See Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong? for why it's recommended against.

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
cigien
  • 50,328
  • 7
  • 37
  • 78