Hello I'm trying to sort a linked list. I'm having some trouble figuring out how to swap an array of char. I know I should have used "string" but this is an assignment for school and we aren't allowed to change it to "string".
Edit: I fixed it I just needed to use "strcpy" to swap the names.
Code:
#ifndef _ASSIGNMENT_9_CPP_
#define _ASSIGNMENT_9_CPP_
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;
struct Node
{
char name[30];
long ID;
Node * next;
Node();
};
class LIST
{
private:
Node *link;
int lsize;
public:
LIST();
void OpenFile(ifstream & myfile);
bool ReadFile(ifstream & myfile);
Node*Nodebuild (char name[], long ID);
void LinkList(Node *ptr);
void sortList();
void showList();
};
LIST::LIST()
{
link = NULL;
}
Node::Node()
{
next = NULL;
}
void LIST::OpenFile(ifstream & myfile)
{
myfile.open("a9.txt");
}
bool LIST::ReadFile(ifstream & myfile)
{
if(myfile.peek() == EOF)
{
return false;
}
char name[30];
long ID;
myfile>>name;
myfile>>ID;
LinkList(Nodebuild(name,ID));
if(myfile)
{
return true;
}
else
{
return false;
}
}
Node *LIST::Nodebuild(char name[],long ID)
{
Node *ptr = new Node;
strcpy(ptr->name, name);
ptr->ID = ID;
ptr->next = NULL;
return ptr;
}
void LIST::LinkList(Node *ptr)
{
if(link == NULL)
{
link = ptr;
return;
}
Node *t_v;
t_v = link;
while(t_v->next!=NULL)
{
t_v = t_v->next;
}
t_v->next = ptr;
}
void LIST::sortList()
{
Node *curr;
char tempName;
for(bool didSwap = true; didSwap; )
{
didSwap = false;
for(curr = link; curr->next != NULL; curr = curr->next)
{
if(curr->ID > curr->next->ID)
{
tempName = curr->name;
curr->name = curr->next->name;
curr->next->name = tempName;
swap(curr->ID, curr->next->ID);
didSwap = true;
}
}
}
}
void LIST::showList()
{
Node *t = link;
while(t != NULL)
{
cout<<t->name<<" "<<t->ID<<endl;
t = t->next;
}
}
int main()
{
LIST myList;
ifstream myfile;
myList.OpenFile(myfile);
while(myList.ReadFile(myfile));
myList.sortList();
myList.showList();
cout<<endl;
return 0;
}
#endif