When reading input file into the array the last line of the input file is not read in. When i run the program everything ouputs except tea and the cost.


input file:

1.45
Bacon and Egg
2.45
Muffin
0.99
French Toast
1.99
Fruit Basket
2.49
Cereal
0.69
Coffee
0.50
Tea
0.75

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

//structure
struct menuItemType
{
	string menuItem;
	double menuPrice;
	bool selected;
};

//prototype declarations
void open(ifstream& fin);
void read(ifstream &fin, menuItemType menu[], int &size); // reads and stores the information into the array of struct

int main ()
{

	ifstream fin;
	ofstream fout;
	menuItemType menu[20];
	int size = 0;



	open(fin);
	read(fin, menu, size);




	for (int q = 0; q < size; q++)
	{
	cout << menu[q].menuItem << endl;
	cout << menu[q].menuPrice << endl;
	}


system("Pause");
return 0;
}

void open(ifstream& fin) //generic open file code...
{
	string finput;

	cout<<"Enter Input File Name: ";
	cin>>finput;

	fin.open(finput.c_str());
	if(fin.fail())
	{
		cout<<"Input File Invalid!!!"<<endl;
	}
}

void read(ifstream &fin, menuItemType menu[], int &size) // read and store the info.
{

{
	int i = 0;

	do
	{
            getline(fin, menu[i].menuItem);
            fin >> menu[i].menuPrice;
            fin.get();      // to get of the eol character after the price
            menu[i].selected = false;
            i++;

	} while (fin);
	
	size = i - 1;
}

}

Line 77, don't subtract 1. This is preventing you from printing out the last item.
What would happen if you only had one item in the file?
i would come out of the loop with the value of 1 and you would subtract 1 leaving size equal to ZERO.
Then in the main nothing would print out because q < size is not true.

This article has been dead for over six months. Start a new discussion instead.