I got a homework in school and I have done it but the result is not exactly what I wanted.
The task is to get sums from a text file with the following rules:
the first column contains numbers
the second is a 0/1 boolean (the separating character is space)
whenever the bool is true in continuous lines, the programme should add up the numbers
The .txt file looks like this:
Input:
20 1
30 1
40 0
50 1
60 1
Desired Output:
50
110
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
double number;
double sum;
int boolean;
sum = 0;
ifstream homework;
homework.open("homework.txt");
while (!homework.eof())
{
homework >> number >> boolean;
if (boolean == 1)
{
sum += number;
}
}
cout << sum << endl;
homework.close();
system("pause");
return 0;
}
I wanted the code to print out 50 and 110 (because there is a line with a false boolean) but instead, the code printed 160 (so it summed up all lines with true boolean).
Any ideas?