Help reading a file

Whenever I run the program, there is an error in opening the input file. I'm not quite sure where I went wrong.
Text2.txt:
2345.45667
-0.0000456
34.9999
0.006788
-1.2345

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
46
  // ConsoleApplication26.cpp : Defines the entry point for the console application.
//
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
#include <iomanip>
using namespace std;

void num(int& a, ifstream &inf, ofstream &ouf);
int main()
{
    int a;
	ifstream inf;
	ofstream ouf;
	inf.open("Text2.txt");
	//ouf.open("Text.txt");
	ouf.open("Text2.txt", ios::app);
	if (inf.fail())
	{
		cout << "Error in opening the input file " << endl;
		exit(1);
	}
	if (ouf.fail())
	{
		cout << "Error in opening the output file " << endl;
		exit(1);
	}
	 num(a, inf, ouf);
	inf.close();
	ouf.close();
	return 0;
}
void num(int& a, ifstream &inf, ofstream &ouf)
{
	while (!inf.eof())
	{
		inf >> a;
		cout.setf(ios::fixed);
		std::cout.precision(3);
		cout.setf(ios::showpos);
		    ouf <<setw(10)<<a;
			cout <<setw(10)<< a;
			cout << endl;
	}
}
Is there a reason why you want to use the same file for input and output ?
Yes, for the online compiler I used I was only able to use one text file. Otherwise, I do not necessarily need to have the same input and output file.
The problem with this approach is when you open the input file the file pointer is at the beginning.
Then you open the output file in append mode and the file pointer is at the end.
How can you read from it ?

One possible solution would be to read all the numbers into a vector first, close the input, open the output and write all the numbers from the vector.
Topic archived. No new replies allowed.