0

First off, thank you for taking the time to read this.

Here is my question:

I am reading data in from a file that contains names for items that I will be placing onto a heap for use in a program.

The program gives me all of the desired data plus one more piece of data (not desired) with no name.

I can't seem to get my while (!eof) to work properly, and any assistance in this matter would be greatly appreciated.

ifstream dfile;
dfile.open ("batteries.dat");
 
while (!dfile.eof())
  {
    std::getline(dfile, name, '\n');
  
    battery.key = 100;
    battery.name = name;

    batteries.insert (battery);
    cout << "Battery " << battery.name << " with " << battery.key
         << "% charge"
         << "\nwas added to your shelf." << endl;

  }
dfile.close();

Again, thank you for your time

Jim

3
Contributors
3
Replies
10
Views
8 Years
Discussion Span
Last Post by JimD C++ Newb
0

Dont use 'eof' as an exit indicator for the loop. eof() is true only after the end of file is read and not when end of file is reached as a result your getting one extra character. use while(file.getline(<args>)) instead of 'eof'.

0

Better use

std::ifstream file(...);
std::string line;
...
while (getline(file,line)) {
...
}
if (file.fail()) { // i/o error occured
...
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.