【问题标题】:gets() does not read user inputgets() 不读取用户输入
【发布时间】:2011-11-21 18:34:34
【问题描述】:

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

在这里我可以填充链表的第一个节点,但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))
  • @runnerup:这是个坏主意:stackoverflow.com/questions/1565496/…
  • 您看到的具体问题是什么?程序会崩溃还是其他原因?
  • function "malloc" 返回一个 void 指针,您应该手动将其转换为 (data*) 类型

标签: c gets


【解决方案1】:

发生这种情况是因为:

ch=getchar();

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

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

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

还应使用函数fgets 代替getsWhy?

【讨论】:

    【解决方案2】:

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

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

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

    1. c-faq
    2. 如果你在 Windows 上,还有这个 mdsn

    还有一点,尽量始终使用 fgets - 而不是 gets-,因为如果使用 get,就不可能防止缓冲区溢出。

    您可以在link 阅读“使用安全库”部分

    【讨论】:

      【解决方案3】:

      你还应该添加一行

       current->next = 0;
      

      之后

       current=current->next;
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        • 2013-01-06
        相关资源
        最近更新 更多