I have a problem with adding elements to deque from text file. File contains numbers such as: 1 2 3 4. But when I try to extract numbers from the file, deque is filled with a one number more.
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <stdio.h>
using namespace std;
int temp;
int br = 1;
struct delem
{
int key;
delem *next;
} *l = NULL, *r = NULL;
void push_l(int n)
{
delem *p;
p = l;
l = new delem;
l->key = n;
l->next = p;
if (r == NULL)
{
r = l;
}
}
void push_r(int n)
{
delem *p;
p = r;
r = new delem;
r->key = n;
r->next = NULL;
if (l == NULL)
{
l = r;
}
else
p->next = r;
}
int pop_l(int &n)
{
delem *p;
if (l)
{
n = l->key;
p = l;
l = l->next;
if (l== NULL)
r = NULL;
delete p;
return 1;
}
else
return 0;
}
int pop_r(int &n)
{
delem *p;
if (r)
{
n = r->key;
if (l == r)
{
delete r;
l = r = NULL;
}
else
{
p = l;
while (p->next != r)
p = p->next;
//p++;
n = r->key;
p->next = NULL;
delete r;
r = p;
return 1;
}
}
else
return 0;
}
void get(int n)
{
int i, t;
for (i = 1; i < br; i++)
{
pop_l(t);
if (i == n)
{
temp = t;
}
push_r(t);
}
}
void print_deque()
{
for (int i = 1; i<br; i++)
{
get(i);
cout << temp << " ";
}
}
void find_number()
{
int n;
int total = 0;
int count = 0;
double average = 0;
ifstream deque_file;
deque_file.open("deque.txt", ios::in);
if (deque_file)
{
while (!deque_file.eof())
{
deque_file >> n;
push_l(n);
}
while(pop_l(n))
{
total+=n;
count++;
}
average = total/count;
cout<<"\n\nSum: " << total << " Count: " << count << " Average: " << average << endl << endl;
}
else
cout << "Error while opening input file!" << endl;
deque_file.close();
}
int main()
{
int ch;
ifstream fd;
fd.open("deque.txt", ios::in);
while (fd)
{
fd >> ch;
push_r(ch);
br++;
}
print_deque();
find_number();
system("pause");
return 0;
}
How to avoid adding the last number twice ?
Don't do while (fd)
(or while (!fd.eof())
).
Instead do while (fd >> ch)
.
The reason is that the eofbit
flag is not set until you try to read from beyond the end of the file for the first time, leading your loop to iterate once to many.