#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?
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
.
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.
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.
To clarify change getchar(); to c = getchar(); on the first line of the inputChar procedure.
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 != '.')
{
...
}
}
精彩评论