i have a coding that need to read from a file. i have to find the sum of 2 column from the file. the file is like this :
Mon 12 5 50
Tue 20 8 13
Wed 20 2 20
Thu 10 4 33
i want to find the sum of column 2 with column 3 and determine for each day either the expenses increase or decrease
i want the output to be : Monday , the expenses are rm 17.
i have wrote the coding but the loop for no change still appear even it should be decrease
You are not doing anything with current_sum or sum. They remain uninitialized. Something like this perhaps?
1 2 3 4 5 6 7 8
double sum = 0;
for (double DAY {}, FOOD {}, TRANSPORT {}, SHOPPING {};
nameFile >> DAY >> FOOD >> TRANSPORT >> SHOPPING; )
{
total = FOOD + TRANSPORT ;
double current_sum = sum + total ;
#include <iostream>
#include <fstream>
#include <string>
void expenses(std::istream& nameFile);
int main()
{
std::ifstream nameFile("money_data.txt");
if (!nameFile)
return (std::cout << " ERROR : cannot open file.\n"), 1;
expenses(nameFile);
}
void expenses(std::istream& nameFile)
{
nameFile.clear();
nameFile.seekg(0);
double prev_sum {-1.0};
std::string day;
for (double food {}, transport {}, shopping {};
nameFile >> day >> food >> transport >> shopping; ) {
constauto day_sum {food + transport};
std::cout << " Day :" << day << " Total expenses : RM" << day_sum;
if (prev_sum >= 0)
if (day_sum > prev_sum)
std::cout << " (increase)";
elseif (day_sum < prev_sum)
std::cout << " (decrease)";
else
std::cout << " (no change)";
std::cout << '\n';
prev_sum = day_sum;
}
}
Day :Mon Total expenses : RM17
Day :Tue Total expenses : RM28 (increase)
Day :Wed Total expenses : RM22 (decrease)
Day :Thu Total expenses : RM14 (decrease)