I'm having a bit of trouble trying to figure out how to get certain values to add up into a total value. This assignment was to create a program that would read values from a provided file. It would then sort them into columns and create an additional column called 'Value'. This would be the Quantity times the Cost values.
The last part would be to add up each value and display a total message. Here is my code.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
usingnamespace std;
int main()
{
//Declare Variables
string name = "";
double quant = 0.0;
double price = 0.0;
double value = 0.0;
double total = 0.0;
//Create file object
ifstream inFile;
//Open File for Input
inFile.open("Advanced25.txt", ios::in);
if (inFile.is_open())
{
//Create columns
cout << "Name" << '\t' << "Quantity" << '\t' << "Price" << '\t'
<< "Value" << endl;
//Get item data
getline(inFile, name, '#');
inFile >> quant;
inFile.ignore(1);
inFile >> price;
value = quant*price;
while (!inFile.eof())
{
//Display Data
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << name << '\t' << quant << '\t'
<< price << '\t' << value
<< endl;
getline(inFile, name, '#');
inFile >> quant;
inFile.ignore(1);
inFile >> price;
value = quant*price;
}//end while
std::cout << "The total inventory value is: " << total << endl;
//Close file
inFile.close();
}
else
cout << "File could not be opened." << endl;
system("pause");
return 0;
}
I have tried a while and a for loop within the current while loop in order to add up the Values. However, that did not work. The total value ended up copying the first item's value when I used the additional while loop. With the For loop, every Value was altered instead of providing a new total.
What am I doing wrong? How should I go about finding the total of these items? I tried both While and For loops at line 50 but removed them since they didn't do anything productive.