views:

88

answers:

5
#include <iostream>
using namespace std;

struct Node
{
    char item;
    Node *next; 
};

void inputChar ( Node * );
void printList (Node *);
char c;

int main()
{

    Node *head;
    head = NULL;
    c = getchar();
    if ( c != '.' )
    {
     head = new Node;
     head->item = c;
     inputChar(head);
    }
    printList(head);
    return 0;
}

void inputChar(Node *p)
{
    getchar();
    while ( c != '.' )
    {
     p->next = new Node;    
     p->next->item = c;
     inputChar(p->next);
    } 
    p->next = new Node; // dot signals end of list    
    p->next->item = c;
}

void printList(Node *p)
{
    if(p = NULL)
     cout << "empty" <<endl;
    else
    {
     while (p->item != '.')
     {
      cout << p->item << endl;
      printList(p->next);
     }
    }
}

I am trying to make a linked list of characters that are input by the user. A period indicates the end of the input. My program keeps looping on the inputChar function. Any ideas?

+2  A: 

Perhaps you should add:

c = getchar();

Still, it's kind of dangerous what you are doing. In some platforms, getchar() will return immediately after consuming the ENTER key of the previous getchar() call. So you should consider that in your loop. Perhaps adding an extra getchar() to the inputChar function?

Also, what Paul wrote is true. You should change your while loop with a simple if.

Pablo Santa Cruz
+2  A: 

Because you never change the value of c inside the loop. So why would it ever break out?

You only set the value of c once before the loop.

Brian R. Bondy
+2  A: 

You have inputChar calling inputChar. When you get X deep into the inputChars and one gets the ., when it returns, its caller still has c equal to whatever it was before it called inputChar, so it continues to loop.

Paul Tomblin
True. Didn't realize that. Perhaps he should change his while loop with a simple if...
Pablo Santa Cruz
No, I think he should change the whole logic to avoid all the recursive calls. They aren't necessary.
Paul Tomblin
How can I rework this problem without recursion? I'm not sure how to use iteration with pointers to create a linked list.
Brandon
+2  A: 

To clarify change getchar(); to c = getchar(); on the first line of the inputChar procedure.

Joe
+1  A: 

Consider something like this, which tests for both a premature end and the designated end-of-line delimiter, and will allow you to specify a different stream than std::cin in the future.

void inputChar(Node *p, std::istream& in = std::cin)
{
    char ch;
    while(in.get(ch) && in && ch != '.')
    {
       ...
    } 
}
meagar