Reid Schneider
Reid Schneider

Reputation: 33

Changing a Value in a Text File c++

I was wondering if there was a way to change a specific line of a text file while you are reading it. I am creating an ATM program and I want to change the amount of money in the persons account when they withdraw or deposit something. I have a text file for the username, password, and balance but all I want to do is change the balance. How would I go about doing that?

Upvotes: 3

Views: 2602

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Changing a line in a text file in place is possible only when the changed text has an identical length byte-for-byte with the original. When this cannot be guaranteed (and it certainly sounds like this is the case in your assignment) one common way that works particularly well when the files are small is to create a temporary file, write the new content into it, then swap the files, and delete the original. One advantage of this method is that your file does not get corrupted if the write operation is stopped in the middle: the temporary file becomes corrupted, while the original stays intact.

Upvotes: 3

gcochard
gcochard

Reputation: 11744

Since this is homework, I'll give you a broad overview of what you should be doing here.

You can read the file in, find the balance, change it, and then write the file back out.

Reading the file in can be done using an ifstream, and the function you'll probably want to use is getline.

You can then write it back out using an ofstream.

Upvotes: 4

Related Questions