pdhimal1
pdhimal1

Reputation: 229

C++ Reading from a text file and calculating total for each line:

I have to write a program in C++ that will read from a text file and calculate total for each lines. The text file looks like this

2
14.4 56.9 54 65.7 86.9
98.6 84.9 34.7 85.5 15.4
24.4 57.9 54.9 70.7 63.5

34.4 16.9 41.9 54.7 84.98
97.6 84.9 14.7 85.5 16.4
23.4 76.9 54.9 74.7 64.5

The first line has the number of weeks. The lines that follow have five doubles each (3 line per each week). ANd it will repeat the number of weeks given in the first line. So far I have this code to calculate the total for each week. SOmehow it gives me 0 as the total before each week

string s; 
 double sum[4]; 

 for(int j = 0; j < weeks; j++)
   {
       for(int i = 0; i <= 3 && getline(in, s); i++)
         {
            istringstream sin(s);
            sum[i] = 0;
            while (sin>>sales)
            {
               sum[i] = sum[i] + sales;
            }
            cout << sum[i] << endl;
         } 
    }

And here's the outcome :

0
277.9
319.1
271.4
0
232.88
299.1
294.4

Can somebody tell me why am i getting that 0? Also how should I store the numbers as total for each line. The number of lines would vary based on number weeks. SOmebody help please!

Upvotes: 1

Views: 3730

Answers (3)

jparimaa
jparimaa

Reputation: 2044

Check that it is not an empty line like this:

 if (!s.empty())
 {
     cout << sum[i] << endl;
 }

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311018

I think the problem is that the number of weeks was read using operator >>. After that the next getline call read an empty string. It would explaing the first zero. Also I see that there is an empty line between two triads of lines. So it seems you again read an empty line. Apart from this I do not understand why you are using the loop

for(int i = 0; i <= 3 && getline(in, s); i++)

if there are only three lines for a week.

So you need check whether an empty line was read.

Upvotes: 0

Daniel Garrett
Daniel Garrett

Reputation: 121

You are summing the numbers for the blank lines between each group. Since there are no number on these lines, the sum of course remains at zero. I also assume that you are not reading in the whole first line to get the number of weeks, so there is a leading zero there too. To solve the problem, simply read an extra line before starting each week, like this:

string s; 
double sum[4]; 

for(int j = 0; j < weeks; j++)
{
    getline(in, s);
    for(int i = 0; i < 3 && getline(in, s); i++)
    {
        istringstream sin(s);
        sum[i] = 0;
        while (sin>>sales)
        {
           sum[i] = sum[i] + sales;
        }
        cout << sum[i] << endl;
    }
    cout << endl;
 }

Output is:

277.9
319.1
271.4

232.88
299.1
294.4

Upvotes: 2

Related Questions