-
infinite loop
Hi,
I've been working on this program for a few hours and i'm getting very frustrated. It will work and then i'll try to do the next part of it, and it will get screwed up again.
The part that i'm having trouble with right now:
the assignment asks to read in a name, phone#, and id#, and to then have it sort all of the information by the id #.
i'm trying to use a bubble sort but it is causing an infinite loop somewhere
at one point, the ids were getting sorted but the rest of the information wasn't. Now, i screwed it up and nothing is getting sorted
this is the file, "student.txt" that i was having sorted:
Lee, Bruce 876-543-9876 78905
Deris, Andi 987-654-3214 54321
Kwestel, Morty 678-543-7465 45678
if anyone could look over the code and help me out, i would greatly appreciate it.
- Thank you
bruce
-
*shrug* Works fine for me. What compiler are you using?
The id's are only getting sorted because you're only exchanging the id numbers and not the actual names of the people. You want to pass exchange() two nodes to exchange, not two id numbers.
Code:
#include "stdafx.h"
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h> //set width to output phone #
#include<stdlib.h>
#define IN ("student.txt")
const int SIZE = 3;
struct node
{
char lastname[20];
char firstname[20];
char phonenum[12];
/*
struct phonenum
{
int areacode;
int num1;
int num2;
*/
double id;
};
void readfile();
void sort(node[], int);
void exchange(node &, node &);
//void search();
void display(node[], int);
int main()
{
readfile();
return 0;
}
void readfile()
{
ifstream fin(IN);
int size = 0;
node info[SIZE]; // 10?
int i =0;
while (!fin.eof())
{
if (i < SIZE)
{
fin >> info[i].lastname;
fin >> info[i].firstname;
fin >> info[i].phonenum;
fin >> info[i].id;
i++;
size++;
}
sort(info, size);
}
display(info, size);
}
void display(node info[], int size)
{
for (int i=0; i < size; i++)
{
cout << info[i].lastname << " " << info[i].firstname << "\t"
<< info[i].phonenum << " " << info[i].id<<"\n";
}
}
void sort (node info[], int size)
{
int top;
bool sorted = 0;
while (!sorted)
{
sorted = 1;
for (top = 0; top < size -1; top++)
{
if (info[top].id > info[top +1].id)
{
exchange(info[top], info[top+1]);
sorted = 0;
}
}
}
}
void exchange (node &x, node &y)
{
node temp = x;
x = y;
y = temp;
}
That WORKS. It will NOT work if there is a new line at the end of your students.txt file. It happened to me when I added another element to test. So, my guess is you have an extra new line at the end of your data file.