Need a project done?

C++ Programming Developer

Search This Blog

Reading Writing from Linked List C++



#include <iostream>
#include <fstream>
#include <fstream>
using namespace std;



struct link{
int data;
link* next;
};

class linkedList{
public:
linkedList();
void addItem(int);
void print(void);
private:
link* head;
link* tail;
};

linkedList::linkedList(){
head = tail = NULL;
}

void linkedList::addItem(int n){
link* temp = new link;
temp->data = n;
temp->next = 0;

if (head == 0 && tail == 0){
head = temp;
tail = temp;
}
else{
tail->next = temp;
tail = temp;
}
ofstream os("linkedList.txt", ios::out | ios::app);
os << "data: " << temp->data << endl;
os.close();
}

void linkedList::print(){
for (link* p = head; p != NULL; p = p->next){
cout << p->data << endl;
}
}

int main(){
ofstream os("linkedList.txt");
os.close();

int n;  
linkedList ll;
cout << "Enter number to insert: (-1 to print): "; cin >> n;

while (n!=-1){
ll.addItem(n);
cout << "Enter number to insert: (-1 to print): "; cin >> n;
}
   
ll.print();

cout << "Linked List has been written in the file and has been printed\nNow printing link List's data using file." << endl;

//READING LINKED LIST FROM FILE.
//////////////
// linkedList LL;
char str;
ifstream is;
is.open("linkedList.txt");
while (is){
is.get(str);
cout << str;
}
is.close();
return 0;
}

No comments:

Post a Comment

"Don't let anyone ever make you feel like you don't deserve what you want."