Hey guys,
I am having trouble getting data from a file into a linked list.
I'm very new to c++ and am finding it difficult to understand but am trying my best.
I need to get a text file and insert each character into a seperate node in a linked list but am gettin nowhere.
I think the problem is with my dnode struct.
And with the part following push_back.
Any help appreciated.

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <list>
#include "dnode.h"

using namespace std;

void loadFile(list<dnode> &myList, const char *file);

int main(int argc, char *argv[])
{
   if (argc != 2) {
      cout << "Syntax : File Error\n";
      return 0;
   }

   list<dnode> myList;

   loadFile(myList, argv[1]);

   return 0;
}

void loadFile(list<dnode> &myList, const char *file)
{
   ifstream fin;
   
   fin.open(file);
   if (!fin) {
      cout << "Unable to read from " << file << "\n";
      exit(0);
   }
   
  while (fin.good())
	  myList.push_back ((char) fin.get());

  fin.close();  
}

and the dnode template

#ifndef DNODE_H
#define DNODE_H

using namespace std;

//template node class for doubly linked list

template <typename dataType> struct dnode 
{
   dataType data;
   dnode *prev, *next;
         
   // constructors
   dnode() : prev(NULL), next(NULL) {
   }
   
   dnode(const dataType& dataItem, dnode *prevPtr, dnode *nextPtr) :
      data(dataItem), prev(prevPtr), next(nextPtr) {
   }
};

#endif

I need to get a text file and insert each character into a seperate node in a linked list

You don't need the dnode construct actually, instead you can simply use std::list<char> myList;

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <list>

using namespace std;

void loadFile(list<char> &myList, const char *file);

int main(int argc, char *argv[])
{
   if (argc != 2) {
      cout << "Syntax : File Error\n";
      return 0;
   }

   list<char> myList;

   loadFile(myList, argv[1]);

   // Use an iterator to display the content
   for(list<char>::iterator it = myList.begin(); it != myList.end(); ++ it)
   {
	   cout << *it;
   }
   return 0;
}

void loadFile(list<char> &myList, const char *file)
{
   ifstream fin;
   
   fin.open(file);
   if (!fin) {
      cout << "Unable to read from " << file << "\n";
      exit(0);
   }
   
  char aChar;
  fin >> noskipws;  // do not skip whitespace

  while (fin >> aChar)   // Reads one char at a time
	  myList.push_back (aChar);

  fin.close();
}

Cheers mate,
It ended up so simple in the end.
I think I always am looking for the most difficult way to solve a problem.

This article has been dead for over six months. Start a new discussion instead.