4

我是链表的新手,现在我在节点数量方面几乎没有问题。

在这里,我可以填充链表的第一个节点,但该gets()函数似乎没有暂停执行以填充下一个节点。

输出如下:

Var name : var
Do you want to continue ?y
Var name : Do you want to continue ?  // Here I cannot input second data

这是我的代码:

struct data
{
    char name[50];
    struct data* next;
};
struct data* head=NULL;
struct data* current=NULL;
void CreateConfig()
{
    head = malloc(sizeof(struct data));
    head->next=NULL;
    current = head;
    char ch;
    while(1)
    {
        printf("Var name : ");
        gets(current->name);    //Here is the problem,
        printf("Do you want to continue ?");
        ch=getchar();
        if(ch=='n')
        {
            current->next=NULL;
            break;
        }
        current->next= malloc(sizeof(struct data));
        current=current->next;
    }
}
4

3 回答 3

7

发生这种情况是因为:

ch=getchar();

从输入中读取yn从输入中读取并分配给但输入缓冲区中有一个换行符,该换行符在下一次迭代ch中被读取。gets

要解决此问题,您需要y/n在用户输入后使用换行符。为此,您可以将另一个调用添加到getchar()

ch=getchar(); // read user input
getchar();    // consume newline

此外,该功能fgets应代替gets. 为什么?

于 2011-11-21T18:41:39.377 回答
2

这正是@codaddict 所说的。您需要清洁缓冲区。

void fflushstdin( void )
{
    int c;
    while( (c = fgetc( stdin )) != EOF && c != '\n' );
}

你可以阅读这个解释得很好的链接:

  1. 常见问题解答
  2. 如果你在 Windows 上,这个mdsn 。

还有一件事,尝试始终使用 fgets - 而不是 gets-,因为如果您使用 get,则无法防止缓冲区溢出。

您可以在此链接上阅读“使用安全库”部分

于 2011-11-21T18:51:30.170 回答
0

您还应该添加一行

 current->next = 0;

 current=current->next;

确保最后一个元素的下一个元素没有悬空。

于 2011-11-21T18:54:53.497 回答