fstream project 2

I find some conceptual problem this code works when different file is made
for .txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  int main()
{
	int n1 , n2 ,n3 ;
ofstream offile("Num.txt");
ifstream infile("Sum.txt");
	if(!infile)
	{
		cout<<"File not found\n";
	}
	while(infile)
	{
		infile>>n1>>n2>>n3;
		offile<<n1<<" "<<n2<<" "<<n3<<" "<<(n1+n2+n3)<<endl;
	}


getch();
}

but makes garbage value when changes in the same file is made for example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
	int n1 , n2 ,n3 ;
ofstream offile("Sum.txt");//same name
ifstream infile("Sum.txt");
	if(!infile)
	{
		cout<<"File not found\n";
	}
	while(infile)
	{
		infile>>n1>>n2>>n3;
		offile<<n1<<" "<<n2<<" "<<n3<<" "<<(n1+n2+n3)<<endl;
	}


getch();
}

Why is there a problem when changes are tried to be made in the orignal file
ofstream offile("Sum.txt");
it means that you are creating object called offile based on ofstream class with constructor, which has two parameters - name of file and mode in which file is opened
When you do not write a mode, it's implicitly ios::out

And what it does is that it deletes existing file Sum.txt and create a new one. And you read unknown nubers from it.

If you want to program not to delete it, write ofstream offile("Sum.txt", ios::app), but then you will have to face
infinite
while loop
simply said, while(infile) is true until you get to the end of the infile file. However, you not only read from, but you write in too. So there is still something to read.
It writes something in it now but there is alot of garbage value in the sum.txt file when opened changes that are made is by adding ios::app to sum offile
Topic archived. No new replies allowed.