Hey guys, so i'm working on a program that has to read a shopping list from a file and then after I need to add tax to it. I've managed to get the first item and price out from the file, but the whole other list doesn't get extracted,i'm assuming I need to use two arrays to solve my issue but when I went and did them nothing would print out and my program would terminate. If i delete the arrays my heading function prints and also the item and price. Any ideas on why it doesnt print anything when I use the arrays? Ps this is my first time posting so if the format is wrong im very sorry.
This is how the file looks like:
Student's Shopping List
apple 0.89
book 135.00
eraser 0.59
flashdrive 7.99
folder 1.29
highlighter 0.98
laptop 500.00
mouse 14.98
notebook 5.00
paper 2.29
pencil 0.35
pen 1.98
water 1.00
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
usingnamespace std;
//function prototypes
void headings();
float tax();
int main() {
constint SIZE=13;
string item[SIZE],dummy;
float cost[SIZE];
ifstream infile("studentList.txt");
getline(infile,dummy); //reads first line, I use this since I dont need the first line in the file
while (!infile.eof())
{
for(int count =0; count < SIZE; count ++)
{
infile >> item[count] >> cost[count]; // my attempt at making the array
}
if (infile.eof()) break;
headings(); //prints out headings
cout << item <<" " << cost << " " << endl;
return 0;
}
return 0;
}
float tax() // dont worry about tax, i didnt really work on it since i couldnt get the numbers
{
constint TAX_RATE= 0.09;
}
void headings()
{
cout << "Item" << setw(16) << " Cost" << setw(10) <<"Tax" << setw(9)<<"Total" << setw(12) << endl; // these are the headings
}
Any ideas on why it doesnt print anything when I use the arrays?
Well, you have a nested loop:
1 2
while (something)
for (something)
That is overdone. Use either a while loop or a for loop but not both - at least when reading from the file.
In any case using eof() as a loop condition is not a good idea - that is to say - don't do it. It can cause unexpected problems and is best avoided. Instead, put the input operation such as iinfile >> item[count] >> cost[count] inside the loop condition.
Here I also checked the array index in the loop condition, to avoid going over the boundary of the array.