【问题标题】:can not read character from user [duplicate]无法从用户读取字符[重复]
【发布时间】:2014-03-25 04:52:58
【问题描述】:

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

   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);

  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;



}

【问题讨论】:

    标签: c scanf


    【解决方案1】:

    这样做:

    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 的下一次调用会读取该换行符。

    【讨论】:

    • 但是为什么呢?这背后的原因是什么?
    • @Kapil - 你按 enter 键对吗? enter 在控制台上做了什么?它添加了一个换行符。
    • 我们可以通过刷新缓冲区来做到吗?
    • @Kapil - fflush 未定义为在输入流上调用。
    • 是的,遇到了同样的问题,谢谢帮助。
    【解决方案2】:

    你只需要在scanf中的%c之前给一个空格

    scanf(" %c",&ch);
    

    这是因为在输入我们按下回车后,输入存储在缓冲区中,并且我们的程序再次读取,有时我们清除我们刷新我们的输入/输出缓冲区,你可以在 Linux 中检查fflush()我认为是功能,有很多方法,但这是我所知道的最简单的方法。 希望对你有用。

    【讨论】:

      猜你喜欢
      • 2013-04-12
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多