Hey everyone,

So in a few of my programs, when I have the user enter input, which then gets stored in a list, there seems to be some error. I use a while loop to allow for continuous input, like

while (!cin.eof()) {
          cin >> value;
          list.insert(value);
    }

so that when they hit CTRL-D, the loop terminates and the list has all of its values.

When someone enters the following values: 1 2 3 4 5
My function prints the values backwards, so when I print the list, I get: 5 5 4 3 2 1

Could someone help me on this? I would greatly appreciate it :)
Here is my code:

list.h

#ifndef LIST_H
#define LIST_H

class List
{
    public:
        List();
        ~List();
        void insert(int value);
        void print();
        void insert_at_end();
        int size();
    private:
        class Node
        {
            public:
                Node(int value, Node *next)
                {m_value = value; m_next = next;}
                int m_value;
                Node *m_next;
        };
        Node *m_head;
        
        int iSize;
};

#endif
list.cpp

#include <iostream>
using namespace std;
#include "list.h"

List::List()
{
    m_head = NULL;
    iSize = 0;
}
List::~List()
{
    // cout << "List::~List() was called" << endl;

    Node *ptr = m_head;
    while (ptr != NULL)
    {
        Node *temp;
    
        temp = ptr;
        ptr = ptr->m_next;
        delete temp;
    }
}

void List::insert(int value)
{
    m_head = new Node(value, m_head);
    iSize++;
}

void List::print()
{
    Node *ptr = m_head; 
    while (ptr != NULL)
    {
        cout << ptr->m_value << endl; 

        ptr = ptr->m_next;
    }
}

int List::size() {
    return iSize;
}
main.cpp

#include <iostream>
using namespace std;
#include "list.h"

int main()
{
    int value;
    // instantiate a List class (the constructor takes NO arguments)
    List list;

    // NOTE:
    // List list();  is incorrect, when there are no arguments don't use ()

    while (!cin.eof()) {
          cin >> value;
          list.insert(value);
    }
    
    // insert numbers into the list
    list.print();
    cout << endl << "size=" << list.size() << endl;

}
while (!cin.eof()) {
          cin >> value;
          list.insert(value);
    }

It seems like the program will store whats in the variable 'value' when Ctrl+D is encountered. Apparently, at the point of Ctrl+D, the final valid value stored in the variable 'value' is 5 which is then inserted into the 'list'. That is why the value 5 appear twice in your list. Change the way input is read and your code should work fine.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.