简体   繁体   中英

Reading incrementing integer from file c++

I have a program that needs to create a file titled "timestamp.txt" and accomplishes this with:

ofstream outstream;
outstream.open("timestamp.txt", ios::app);

I need this file to be created once and have the initial value of 1. This number then needs to be incremented.

When the file is created, I can use:

outstream << "1";

to put the number 1 in the file. How can I do this one time at the creation of the file so that the value is not reset every time the program runs?

I then need to store this value of 1 in local variable time. This can be done at the first execution of the program, but on following executions, how can I pull the numeric value out as an integer and store it in variable time?

Following the execution of the beginning of my program, a local variable time is incremented and must then be put back into timestamp.txt.

ofstream outstream;
outstream.open("timestamp.txt", ios::in);
outstream << time;

Edit: I am very inexperienced with C++. I am pleased to find that I come off knowing more about io than I truly do. I am comfortable with the interworking of ofstream much, much more than I am with ifstream. Using:

ifstream instream("timestamp.txt");
if (instream.good())
{
    getline(instream, timestamp);
    time = timestamp;
}

I can retrieve the string value for the first line in timestamp.txt, but I need this value as an integer not as a string.

If you want to get a integer from a file, you can use:

stoi(string);

which will return a integer from a string.

Here is a live demo: https://ideone.com/R8KIyP

Note that stoi will only work with C++11 and above, so if you don't have C++11, you can alternatively use C++'s stringstream.

You can also refer to this question for more details: How to parse a string to an int in C++?

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