# Help Needed With C++ File Input/Output



## dcf-joe (Mar 11, 2010)

The purpose of the program is written at the top in the comment statements. My problem is with the second half, with the file output. I have tried the file input part by itself, and it works. I have commented that out, and tried the file output part by itself, and it works. But, when I put the two together, the program will not read/write to the file.


```
/* Joshua McCullough
   3/11/10
   Programming Exercise 12.8 - This program will use data files to
                               track how many times a program has
                               been executed.
*/
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	int counter;

	fstream inout;

	inout.open("Exercise12_8.dat", ios::in);
	inout >> counter;
	inout.close();
	
	inout.open("Exercise12_8.dat", ios::out);
	inout << counter++;
	inout.close();


	return 0;
}
```


----------



## dcf-joe (Mar 11, 2010)

I fixed it! I forgot to clear the stream between input and output using "inout.clear();"

I then had to change "counter++" to "++counter" in order to get it to work.


----------



## dazed554 (Mar 11, 2010)

counter++ returns the current value of counter and then increments the variable.
You want to use counter+1 or ++counter if you need it to maintain the value for another part of the program.

I would recommend not to use variable++ or ++variable as values since the exact result is not always clear.

you should use this:
counter++;
inout << counter;

this would also work though:
inout << ++counter;


----------

