cvandal
cvandal

Reputation: 794

C++ Trouble doing simple addition in while() loop

Hopefully someone can tell me what I'm doing wrong. I'm reading up to a specific point on each line within a text file and then trying to add that value to the value on the next line and continue doing so until the end of the file/loop. But at the moment, it will only add the values from the first two lines and not...

123 + 456 + 789 = totalPayroll.

My code is as follows:

inStream.open("staffMembers.txt");

while(getline(inStream.ignore(256, '$'), line))
{
    totalPayroll = stoi(line) + stoi(line);
}

inStream.close();

cout << "$" << totalPayroll << endl;

My text file is formatted as follows:

1 | Person One | $123
2 | Person Two | $456
3 | Person Three | $789

Upvotes: 1

Views: 270

Answers (2)

j883376
j883376

Reputation: 1135

As chris mentioned in his comment, totalPayroll += stoi(line); should solve your problem.

The C++ operator += is a shorthand way of writing totalPayroll = totalPayroll + stoi(line);. It adds the value given on the righthand side of the operator to the current value of the variable.

Upvotes: 2

Qaz
Qaz

Reputation: 61910

In your loop, you're reassigning totalPayroll the value of stoi(line) + stoi(line) for every line, so it ends up finally being 2*789.

You need to keep a continuous sum:

totalPayroll = totalPayroll + stoi(line);

This also has a short form using a compound assignment operator, which does the same thing:

totalPayroll += stoi(line);

Upvotes: 5

Related Questions