Reputation: 35
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?
Upvotes: 1
Views: 72
Reputation: 48278
You have many choices, one could be:
1st one: define the boolean variable as exactly that (a bool variable) and compare those against a true false
example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
bool boolean;
double number{ 0 };
double sum{ 0 };
ifstream homework;
homework.open("hw.txt");
while (!homework.eof())
{
homework >> number >> boolean;
if (boolean)
{
sum += number;
}
}
cout << sum << endl;
homework.close();
return 0;
}
to stop the while when a false is found you can use a break
if (boolean)
{
sum += number;
}
else {
break;
}
Upvotes: 0
Reputation: 7220
The problem is that you do not output until the file has been iterated completely, so you see the total sum, and not the sum after each false
boolean value. If you want sub totals every time you encounter a boolean false
you need to add something to your loop:
while (homework >> number >> boolean)
{
if (boolean)
{
sum += number;
}
else
{
cout << sum << endl;
sum = 0;
}
}
Btw. how is your boolean variable boolean
declared, does your code even compile? I have changed the check in my sample (removed the == 1
).
Upvotes: 3
Reputation: 1
You need to put the line cout << sum << endl;
in an else case inside the while loop, as well as reset the sum.
Something like this should do:
while (!homework.eof())
{
homework >> number >> boolean;
if (boolean == 1)
{
sum += number;
}
else
{
cout << sum << endl;
sum = 0;
}
}
Upvotes: 0