Could anyone tell me why this code read an extra line? It duplicates some of the last line, only it changes the number. For example, the text file (set up as an inventory file) reads:
45 car
23 bus
1 truck
4 van
After running the program, it displays that, but the last line it adds:
0 van
Here's the code I have so far:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
const int SIZE = 500;
struct Inventory
{
int itemNumber;
string itemName;
};
int main(int argc, char *argv[])
{
char filename[20];
ifstream in_stream;
struct Inventory items[SIZE];
cout << "Enter a filename to load: ";
cin >> filename;
in_stream.open(filename);
if (in_stream.fail()) {
cout << "Failed" << endl;
}
else {
cout << "File opened sucessfully." << endl;
}
string data, junk;
int n = 0;
char next_symbol, number[15];
do {
int i = 0;
do {
in_stream.get(next_symbol);
number[i] = next_symbol;
i++;
} while (next_symbol != ' ');
items[n].itemNumber = atoi(number);
getline(in_stream, data);
items[n].itemName = data;
cout << endl << items[n].itemNumber << setw(15) << items[n].itemName;
n++;
} while (! in_stream.eof());
in_stream.close();
system("PAUSE");
return EXIT_SUCCESS;
}