无法从用户读取字符 [英] can not read character from user

查看:44
本文介绍了无法从用户读取字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我正在创建一个二叉树,直到用户需要节点数.但是在从用户那里获取输入时,它在某处失败了..

here in this code i am creating a binary tree until user wants number of nodes. but while getting input from user it fails somewhere..

   struct node *createTree(struct node *root)
{
  int n;
  char ch;
  struct node *t1;
  t1=(struct node *)malloc(sizeof(struct node));
  printf("Enter Element\n");
  scanf("%d",&n);
  if(root==NULL)
    {
  t1->data=n;
  t1->left=NULL;
  t1->right=NULL;
  root=t1;
    } 

  printf("do you want to add node at left?\n");

这不能正常工作

scanf("%c",&ch);

scanf("%c",&ch);

  if(ch=='y')
    {
      t1->left=createTree(t1->left);

    }


   printf("do you want to add node at right?\n");
   scanf("%c",&ch);

   if(ch=='y')
    {
      t1->right=createTree(t1->right);

    }




  return root;



}

推荐答案

这样做:

printf("do you want to add node at right??!\n");
scanf("%c",&ch);
while (getchar()!='\n');  //<-- eat up trailing newline chars - Reads all characters of the line until the end of line is found.

当您在输入键盘输入后按 Enter 键时 - 缓冲区中会保留一个尾随换行符,下次调用 scanf 时会读取该换行符.

When you press enter after entering a keyboard input - there stays in the buffer a trailing newline character which the next call on scanf reads.

这篇关于无法从用户读取字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆