When switching between input and output for a filestream without an intervening seek, you get undefined behavior. It doesn't matter where you seek to but you need to seek! For example, you can seek to zero characters away from the current position or, more likely, back to the position where the value actually started:
std::streampos start = input.seekg(0, std::ios_base::cur); if (input >> balance) { input.seekp(start); input << (balance - amount); }
Note, however, that the stream won't make space for additional characters, i.e., if what you read is shorter than what you write, you'll overwrite data following the originla input. Likewise, you will only overwrite the characters you overwrite. I'd recommened against doing anything like that. If you want to update a file, make sure you are using fixed width records!
Of course, you also shoudn't use input.eof() to verify if the stream is any good: if the stream goes into failure mode, e.g., due to a misformatted input, you'll never reach the point where input.eof() yields true, i.e., you'd get an infinite loop. Just use the stream itself as condition. Personally, I would use something like
while (input >> balance && Balindex != index) { ++Balindex; }
balancetwice to the same value and then overriding it's contents?while (!file.eof()), it won't work as you expect it to. The reason being that theeofbitflag isn't set until after an input operation fails.