-1

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.

  • 1
    Have you made any attempts to write the program yourself? If so, could you post the code you have written? You seem to have a handle on io. – MGM_Squared Oct 11 '15 at 23:25
  • read, integer, file, c++ - you have all the keywords you need. Why don't you do a web search? – Karoly Horvath Oct 11 '15 at 23:37
  • `c++ string to integer` - again, search. I promise it takes less time than asking a question. And don't waste our time with all the irrelevant details if a simple conversion is all you need. – Karoly Horvath Oct 11 '15 at 23:39

1 Answers1

0

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++?

Community
  • 1
  • 1
Patrick Yu
  • 972
  • 1
  • 7
  • 19