2013-08-16 108 views
0

有谁知道下面的代码可能是什么问题?当我运行它,我得到以下的输出:链接列表问题

Insert a value in the list: 1 
Do you want to continue? y/N: 
1 -> 

的事实是,do-while循环执行,直到scanf("%c", &ch)语句,然后它跳了出来(所以我不能提供的ch变量的任何输入) 。我试着用GDB进行调试,我得到了一些奇怪的信息:

GI___libc_malloc (bytes=16) at malloc.c:malloc.c: No such file or directory. 

此外,它说,编译器找不到vscanf.c文件。有没有人对这种奇怪的行为有解释?谢谢! (其目的是为了以倒序打印单链表的值。)

#include <stdio.h> 
#include <stdlib.h> 

struct node{ 
    int info; 
    struct node* next; 
}; 

struct node* head = 0; 

void add_node(int value){ 

    struct node* current = malloc(sizeof(struct node)); 
    current->info = value; 
    current->next = head; 
    head = current; 
} 

void print_node(struct node* head){ 

    while(head){ 

      printf(" %d -> ", head->info); 
      head = head->next; 
    } 

    printf("\n"); 
} 

int main(void){ 

    int val; 
    char ch; 

    do { 

     printf("Insert a value in the list: "); 
     scanf("%d", &val); 
     add_node(val); 
     printf("Do you want to continue? y/N: "); 
     scanf("%c", &ch); 

    } while(ch == 'y' || ch == 'Y'); 

    printf("\n"); 
    print_node(head); 
    return 0; 
} 
+0

这里是一个完整的镜头,第二个'scanf'可以在换行符中读取吗? –

+0

将add_node的方法签名更改为接受struct node *参数,然后将head的地址作为参数传递给您的函数调用。这应该做到这一点。 – Clocks

+0

GDB消息用于通知您无法步入GLIB文件,只需按c继续。 – Clocks

回答

0

您遇到的问题是因为您输入的值为val然后按回车键,则\n仍然保留在输入缓冲区中。因此,下一个scanf假定仍然在输入缓冲器中的\n是它的输入,并消耗它然后循环退出。

其他解决方案: -

1)scanf("%d%*c",&val);

这将第一输入字符分配给val并在那之后事情会被吃掉。因此,\n不会进入下一个scanf

2)scanf("%[^\n]%*c",&val);

这将分配什么的val除了\n然后\n会被吃掉。

2

如果你想输入一个新行(这似乎是你做的)分离,然后更改格式你如何阅读你的角色。更改如下:

scanf("%c", &ch); 

...这样的:

scanf("\n%c", &ch); // << Note, \n to pickup newline before reading the value. 
+0

如果这实际上是问题,他不能只是做'scanf(“%d \ n”,&val);'而不是做两个'scanf's? –

+0

当你做'scanf(“%d \ n”,&val); ',程序等待输入内容之外的东西,它只是在你输入内容后打印并退出。 – sha1

+0

@Jacob,我知道在后面使用'\ n'',谢谢。但是,正如我所知,'scanf()'忽略'\ n''字符。我错了吗? – sha1

2

您可以在if-else块检查正确的输入,并相应地执行代码。 例如,这里是东西,如果我需要检查用户是否希望继续与否,我会做:

char chTemp; //Declare a test variable to check for newline 
printf("Do you want to continue? y/N: "); 
if (scanf("%c%c",&ch,&chTemp) != 2 || chTemp != '\n') 
{ 
    printf("Error in input (Integer input provided)"); 
} 
else 
{ 
    //Do stuff. 
} 

它不仅将解决你的问题,但它也将检查粗心的整数输入。