How to read and write into the SAME file

Hey guys, I'm having trouble writing into the file.
The purpose of my homework is to read numbers from a file, then write three numbers into that same file.

So far the reading part works then when it comes to writing to the file it just doesn't work , it like completely ignores the cin part


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
	int numbers;

	fstream outFile("results.txt", ios::in | ios::out);

	if (!outFile)
	{
		cout << "File did not open \n";
		exit(1);
	}

	cout << "Here are the numbers in the file: \n";

	while (!outFile.eof())
	{
		outFile >> numbers;
		cout << numbers << endl;
	}

	cout << "Enter three more numbers: \n";
	
	for (int i = 0; i < 3; i++)
	{
		outFile << numbers <<endl;
	}

	cout << endl;
	outFile.close();

	return 0;
}
Last edited on
while (!outFile.eof()) Aside from fact that it is wrong and error-prone, after your loop finishes failbit and eofbit will be set on stream. Failbit in particulat means that all further read or write operations would fail automatically. You need to clear stream state. Also when you switch between reading/writing, you need to see to the position you want to read/write by seekp/seekg
Where would seekp() be written in the code?
My guess is before line 26.
Since I am using seekp() to write into the file would I have to use seekg() in the beginning of the code (line 19) to declare I am reading off from a file?

What is wrong with the while statement, I'm using eof() to extract the numbers that are in that file to be displayed.
Do not loop on eof: http://stackoverflow.com/a/21656/1959975
Loop on the input operation itself.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
	int numbers;
	ifstream inFile("PI.txt", ios::in | ios::out);
	if (!inFile)
	{
		cout << "File did not open \n";
		exit(1);
	}
	else
	{
		cout << "Here are the numbers in the file: \n";
	
		while (!inFile.eof())
		{
			inFile  >> numbers;
			cout << numbers << endl;
		}
		inFile.close();
	}

	ofstream outFile ("PI.txt");
	if (!outFile)
	{
		cout << "File did not open \n";
		exit(1);
	}
	else
	{
		cout << "Enter three more numbers: \n";
		for (int i = 0; i < 3; i++)
		{
			outFile << i <<endl;
		}
		cout << endl;
		outFile.close();
	}
	
return 0;
}
Last edited on
Topic archived. No new replies allowed.