can not read character from user [duplicate]

2019-03-04 19:06发布

问题:

This question already has an answer here:

  • scanf() leaves the new line char in the buffer 4 answers

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

this is not working properly

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;



}

回答1:

Do this:

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.

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.



回答2:

You have to just give one space before %c in scanf

scanf(" %c",&ch);

This is because after giving the input we pressed enter that enter is stored in buffer and this read again by our program, some time we clear we flush our input/output buffer you can check in Linux fflush()I think so is the function, there is lots of way but this is the easiest way that I know. Hope useful for you.



标签: c scanf