gets()不会读取用户输入

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;
    }
}

也许你需要进行类型转换,在每个 malloc 前添加 (data *),像这样:(data *) malloc(sizeof(struct data)) - behzad.nouri
@runnerup:那是个坏主意:https://dev59.com/iXI_5IYBdhLWcg3wAeLl - ChrisWue
你具体看到了什么问题?程序崩溃了还是其他什么情况? - ChrisWue
函数“malloc”返回一个无类型指针,您应该手动将其转换为(data*)类型。 - zebrilo
3个回答

7
这种情况发生的原因是:
ch=getchar();

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

为了解决这个问题,您需要消耗用户输入的y/n后面的换行符。为此,您可以添加另一个getchar()调用:

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

同时,应该使用函数fgets替换gets为什么?


2

正如@codaddict所说,您需要清除缓冲区。

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

您可以阅读以下链接,它们非常好地解释了此问题:

  1. C-FAQ
  2. 如果您正在使用Windows,则可以参考MSDN

另外一件事是,请尽可能使用fgets而不是gets,因为使用gets无法防止缓冲区溢出。

您可以阅读该链接的“使用安全库”的部分:这里


0

你还应该添加一行类似于

 current->next = 0;

之后

 current=current->next;

为了确保最后一个元素的下一个元素不会悬空。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接