我正在使用 c 中的双向链表来制作树。
我在该函数中使用递归调用,但不知何故它不起作用。
我的代码是:
struct node
{
int data;
struct node *right;
struct node *left;
};
struct node* getNode()
{
struct node *temp;
temp= (struct node *)malloc(sizeof(struct node));
temp->right=NULL;
temp->left=NULL;
return temp;
}
在下面的函数中我遇到了问题。
struct node* maketree()
{
struct node *t;
t=getNode();
int value;
char choice1='n',choice2='n';
printf("\nenter the value to the node");
scanf("%d",&value);
t->data=value;
printf("\nis there any left child??\n");
scanf("%c",&choice1); // I think here my problem is .
if (choice1 == 'y')
{
t->left=maketree();
}
printf("\nis there any right child??\n");
scanf("%c",&choice2);
if (choice2 == 'y' || choice2 == 'Y')
{
t->right=maketree();
}
return t;
}
int main (void)
{
struct node *t;
t=maketree();
return;
}
代码编译正确,但问题是,代码不等待我的选择(我使用scanf()
,C 应该等到我向终端输入输入。)
但输出是:
enter the value to the node4
is there any left child??
is there any right child??
请协助。
The scanf("%d", &value)
留下换行符;这scanf("%c", &choice1)
读取该换行符。
检查返回值scanf()
每次。并打印您所阅读的内容以帮助您调试代码。确保你的程序得到了你认为它得到的东西。
一个简单的修复方法是替换第二个scanf()
with scanf(" %c", &choice1)
。格式字符串中的空白会占用空格(包括换行符),并读取第一个非空白字符。当然,它也会留下换行符。
正如评论中所暗示的,通常通过以下方式更容易控制事情:
char line[4096];
if (fgets(line, sizeof(line), stdin) == 0)
...deal with EOF...
然后你可以使用sscanf()
来解析该行。这种通用技术比使用scanf()
直接地;当您将整行内容包含在错误报告中时,连贯地报告错误也会容易得多。当您每次调用读取多个转化时,这一点就更重要scanf()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)