Question:
Write a C++ or C program to read integers from a file and put them in a linked list?
Saiyon
2010-04-05 17:54:47 UTC
Use a filestream to get a list of integers from a file and put them into a linked list. Sort the linked list from highest to lowest number and then print the sorted list. Allow user to specify the name of the text file as a command line argument.

This is what I have so far: It will compile, but the program crashes after going through the first number. Furthermore, I haven't gotten to sorting my linked list yet.

// reading a text file
#include
#include
#include
using namespace std;

int data = 0;
int info = 0;
int node_number = 1;

typedef struct node
{
string line; // will store information
node *next; // the reference to the next node
};

int main () {
string line;
node *head = NULL;
node *temp;
temp = (node*)malloc(sizeof(node));
temp->line = info; // store data(first field)
temp->next=head; // store the address of the pointer head(second field)
head = temp; // transfer the address of 'temp' to 'head'
ifstream myfile ("test.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
node *temp1; // create a temporary node
temp1 = (node*)malloc(sizeof(node)); // allocate space for node
temp1 = head;

for( int i = 1 ; i < node_number ; i++ )
{
temp1 = temp1->next; // go to the next node

if( temp1 == NULL )
{
cout< break;
}
}
node *temp; // create a temporary node
temp = (node*)malloc(sizeof(node)); // allocate space for node
temp->line = info; // store data(first field)
temp->next = temp1->next; //transfer the address of temp1->next to temp->next
temp1->next = temp; //transfer the address of temp to temp1->next
node_number++;
cout << line << endl;
}
myfile.close();
}

else cout << "Unable to open file";

return 0;
}

Help is appreciated. Feel free to ignore my approach. 10 points to whoever gets me to a working program.
Seven answers:
cja
2010-04-09 09:52:44 UTC
As usual, Cubbi gives the ultimate STL solution; thumbs up for that. Given your attempt so far, I'll assume you need to build the linked list yourself.



It's odd that your linked list node does not have an integer element, when you say you're supposed to create a linked list of integers. It's not at all clear how you're getting the integers from the input file. Also, you should probably not be using malloc in C++. Here's a working program for you:



#include

#include

#include

#include



using namespace std;



typedef enum { ASCENDING, DESCENDING } SortOrder;



struct listNode {

    int val;

    struct listNode *next;

    bool operator<(const struct listNode &n2) const {

        return this->val < n2.val;

    }

    bool operator>(const struct listNode &n2) const {

        return this->val > n2.val;

    }

};



struct listNode *newListNode(int val);

void deleteList(struct listNode *);

bool nodeSwap(struct listNode *, struct listNode *);

void listSort(struct listNode *head, SortOrder order);

void printList(struct listNode *);

 

int main(int argc, char *argv[]) {

    struct listNode *head,*p;

    string filename,in;

    stringstream ss;

    int n;



    cout << "Enter filename: ";

    getline(cin,filename);

    ifstream inFile(filename.c_str());

    if (inFile.is_open()) {

        p = head = newListNode(-1);

        while (inFile) {

            getline(inFile,in);

            ss.clear(); ss.str(in);

            while (ss >> n) {

                p->next = newListNode(n);

                p = p->next;

            }

        }

        inFile.close();

        cout << endl;

        printList(head);

        cout << "sorted ascending ..." << endl;

        listSort(head,ASCENDING);

        printList(head);

        cout << "sorting descending ..." << endl;

        listSort(head,DESCENDING);

        printList(head);

        deleteList(head);

    } else {

        cout << filename << " not found." << endl;

    }

    return 0;

}

 

//

// Selection sort to arrange the elements of

// the given linked list of listNode structs

// in the specified order.

//

void listSort(struct listNode *head, SortOrder order) {

    struct listNode *i,*j,*min;



    for (i = head; i->next != NULL; i = i->next) {

        min = i;

        for (j = i->next; j->next != NULL; j = j->next) {

            if (order == ASCENDING) {

                if (*(j->next) < *(min->next)) min = j;

            } else {

                if (*(j->next) > *(min->next)) min = j;

            }

        }

        nodeSwap(i,min);

    }

}



//

// nodeSwap: exchange p->next and q->next

//

bool nodeSwap(struct listNode *p, struct listNode *q) {

    struct listNode *t1, *t2, *t3;

    bool swapped = false;

    if (p != q) {

        t1 = p->next; t2 = q->next; t3 = q->next->next;

        p->next = q->next;

        q->next = t1;

        t2->next = t1->next;

        t1->next = t3;

        swapped = true;

    }

    return swapped;

}



//

// newListNode: create new struct listNode

//

struct listNode *newListNode(int val) {

    struct listNode *n = new listNode;

    n->val = val;

    n->next = NULL;

    return n;

}



//

// deleteList : free all memory allocated for the list

//

void deleteList(struct listNode *head) {

    struct listNode *p = head, *q;

    while (p != NULL) {

        q = p->next;

        free(p);

        p = q;

    }

}



//

// printList: display the list

//

void printList(struct listNode *head) {

    struct listNode *p = head->next;

   

    cout << "List: ";

    while (p != NULL) {

        cout << p->val << ' ';

        p = p->next;

    }

    cout << endl << endl;

}



#if 0



Sample run:



Enter filename: nums8.txt



List: 10 4 6 5 8 11 3 20 7 15 12



sorted ascending ...

List: 3 4 5 6 7 8 10 11 12 15 20



sorting descending ...

List: 20 15 12 11 10 8 7 6 5 4 3







Where:



$ cat nums8.txt

10 4 6 5

8

11 3 20



x y z



7 15 12





#endif
2016-12-25 00:57:20 UTC
1
?
2016-04-30 23:15:19 UTC
If you have a problem to helping your child that's difficulty reading, no real matter what age she\he this system is things you need, Children Learning Reading from here https://tr.im/Tg5xQ .

Children Learning Reading is different from other applications because it generally does not rely on teaching phrases by view, a technique that depends on children recognizing and memorizing words by their content and structure. You may have observed (or also bought!) classes that promote full word recognition learning, these programs frequently need you to stay your child before a television or computer monitor for an important amount of time in order in order for them to understand phrases which will let them to start their studying journey.

With Children Learning Reading your child can only have to spend 5\15 minutes at day and he\she will learn how to build the phrase creating the entire procedure for understanding how to learn much more effectively.
?
2010-04-06 21:07:04 UTC
You said "feel free to ignore my approach" :)



#include

#include

#include

#include

using namespace std;

int main(int ac, char** av)

{

//Allow user to specify the name of the text file as a command line argument.

if(ac!=2) {

cout << " Usage: " << av[0] << " filename" << endl;

return 1;

}

//Use a filestream

ifstream f(av[1]);

//to get a list of integers from a file and put them into a linked list.

istream_iterator i(f);

list l(i, istream_iterator());

//Sort the linked list from highest to lowest number

l.sort();

//and then print the sorted list.

copy(l.begin(), l.end(), ostream_iterator(cout, " "));

cout << endl;

}
2014-09-17 21:51:09 UTC
Ehm..

For a simple, step-by-step program that can help your child learn to read visit this site: http://readingprogram.toptips.org



Learning to read at a young age is important for the development of the child. It helps them develop a better understand of their surroundings, allows them to gather information from printed materials, and provides them with a wonderful source of entertainment when they read stories and rhymes. Children develop at different rates, and some children will develop reading skills quicker than other children; however, what's important is that as the parent, you are keenly aware of your child's maturity and reading level to provide them with appropriate books and activities to help them improve.



As parents, you are the most important teacher for your children.



Also Watch this video of a 2 year old child reading http://readingprogram.toptips.org

Regards
2016-04-14 07:04:05 UTC
Put your unrunnable program? I will assit to resolve the issue.
Srividhya
2014-01-09 03:00:58 UTC
Hi cja,

I tried the same code but with strings and it does not work.... Could you please tell me why it does not work with string. I changed 'int val' to 'string val'. Thanks


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...