1

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
3
  • 8
    Did you mean totalPayroll += stoi(line);? Commented May 6, 2013 at 3:33
  • That it exactly what I wanted. Thank you! Would you mind explaining what += means exactly in an answer and I'll mark it as correct. Commented May 6, 2013 at 3:37
  • a+=b is equivalent of a = a+ b Commented May 6, 2013 at 3:39

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

why do you post an answer when someone has already pointed it out in the comments?? just for points? :)
@Bill, I should have figured that would be it from the beginning and went straight for an answer. As it is, I posted one just before j883376. It's entirely possible mine wasn't even noticed.
I was elaborating on what chris pointed out in his comment, since cvandal was unsure what += meant. Since chris made an answer himself a couple seconds before I hit submit, he got upvoted accordingly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.