Fstream double print

In this code the last line is always printed 2 times why is that how can i solve it assume that in text file the data is :
1
2
3


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
47
48
49
50
51
52
53
54
55
56
57
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
struct node
{
	int data;
	
node *next;
};
node *temp=NULL;
node *head =NULL;
void insert(int t1)
{
	
	node *newNode =new node;
	newNode->data=t1;
	if(head ==NULL)
	{
		
		head=newNode;
		temp=newNode;
		temp->next=NULL;
		
	}
	else
	{
		
		temp->next=newNode;
		newNode->next=NULL;
		temp=newNode;
	}
}
void Traverse()
	{
		node *temp=head;
	while (temp!=NULL)
		{
			cout<<temp->data<<endl;
			temp=temp->next;
		}
}

int main()
{
	int id;
	ifstream fin;
	fin.open("lab.txt",ios::in);
	while(!fin.eof())
	{
		fin>>id;
		insert(id);
		
	}
Traverse();
	getch();
}
Don't loop on eof(); instead, loop on fin>>id.
What are you looking for the program to do, i get an error when running it it says there's a error in the conio.h file on line 131
But that way it gives me only one output and if i don't use do while loop it doesn't show any result
1
2
3
4
5
6
7
8
9
10
11
12
13
int mid;
	string mname;
	ifstream fin;
	fin.open("Data.txt",ios::in);
	do
	{
		fin>>mname;
		fin>>mid;
		insert(root,root,mid,mname);
		
	}while(fin>>mid);
Inorder(root);
	getch();
46
47
48
49
50
51
52
int mid;
string mname;
ifstream fin("lab.txt",ios::in);
while (fin >> mname >> mid)
{
    insert(root, root, mid, mname);
}
Last edited on
What happens when you do fin>>X in the condition is the same as anywhere else; if you look at your loop body you will notice that each loop are you are reading into mid twice! Once on line 8 and again on line 11.

Looking at your code from your initial post, you could replace:
1
2
3
4
5
while(!fin.eof())
{
	fin>>id;
	insert(id);
}

With:
1
2
3
4
while(fin>>id)
{
	insert(id);
}
Yes , Thank you it's working but why does it give such error when i use eof();
Because eof() isn't set to be false until you have tried and failed to read from the file; when you try and fail in your original code, it tries to print after then as well.
Topic archived. No new replies allowed.