简体   繁体   中英

Writing an integer into an ifstream C++

Okay, so, I can now read from.txt files as variables, but how do I write the integers once changed back into my text file? Example:

xps.open ("xp.txt"); //Text file is loaded and applied to ifstream 'xps'
int xp;
xps >> xp; //xps is applied to integer xp
xp += 50; //xp has 50 added to it's value

and then I want the value of xp to be written (overwriting the previous number) into xp.txt, so how would I do this?

You need to open the text file for both reading and writing; declare xps as an fstream and then you can just do

xps << xp

It's inefficient to write and overwrite the same value. Just wait until you know what value you want to write to the file, and write it.

I presume you mean ofstream rather than ifstream since you are writing to the file in this question. If you absolutely have to go back in the file then you need to call seekp() . In order to do this you need to remember the point in the file to start writing to which you can get by calling tellp() . So, if you want my advice, try not to have to re-write the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM