gets()不读取用户输入

时间:2011-11-21 18:34:35

标签: c gets

我是链接列表的新用户,现在我在节点数量方面遇到的问题很少。

这里我可以填充链表的第一个节点,但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;
    }
}

3 个答案:

答案 0 :(得分:7)

这是因为:

ch=getchar();

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

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

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

此外,应使用函数fgets代替getsWhy?

答案 1 :(得分:2)

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

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

您可以阅读这些解释得非常好的链接:

  1. c-faq
  2. 如果您在Windows上,请mdsn
  3. 还有一件事,试着总是使用fgets - 而不是gets-,因为如果你使用gets,就不可能防止缓冲区溢出。

    您可以在此link

    上阅读“使用安全库”部分

答案 2 :(得分:0)

你还应该添加像

这样的行
 current->next = 0;

 current=current->next;

确保最后一个元素的下一个不是悬空。

相关问题