0

when I run the code in the command line all the functions work precisely beside the print function. I want print() to print the nodes when I type p and hit enter, yet it doesn't print until I type a character after that. Can you possibly spot my mistake since I can not figure this out?

print() Method

void print(struct node *root)
{
    if (root != NULL)
    {
        printf("(");
        print(root->left);
        printf("%d", root->data);
        print(root->right);
        printf(")");
    }
}

main() Method

int main(int argc, char** argv)
{
    char input;
    int n;
    char insertt = 'i';
    char printt = 'p';
    char searchh = 's';
    char deletee = 'd';
    
    struct node *root = NULL;
    while(scanf("%c%d", &input, &n) !=-1)
    {
        if(input==insertt)
        {
            root = insert(root,n);
        }
        else if(input==deletee)
        {
            root = deleteNode(root,n);
            
        }
        else if(input==searchh)
        {
            if(search(root,n))
                printf("present\n");
            else printf("absent\n");
        }
        else if(input==printt)
        {   
            print(root);
        }       
    }
    return 0;
}
  • 1
    Does this answer your question? [scanf Getting Skipped](https://stackoverflow.com/questions/14484431/scanf-getting-skipped) – kaylum Oct 17 '21 at 04:08
  • Try changing `"%c%d"` to `" %c%d"`. Read the duplicate post for more explanation. – kaylum Oct 17 '21 at 04:09

1 Answers1

0

Look at "%c%d" (%c for a char input and %d for an integer) in while(scanf("%c%d", &input, &n) !=-1 in your code. You are asking for a character and then an integer that as an input. So you will have to provide two inputs together, a first a character and second an integer.

The reason why entering a character instead of integer as the second input works is because you can always input a character for an integer and its ascii value (an integer) would be taken by the C compiler (although I guess this behavior can be controlled/modified in modern compilers).

Anurag Ambuj
  • 101
  • 1
  • 7
  • I seperated the while loop into two separate lines, now my data is not being inserted – Kush Patel Oct 17 '21 at 05:12
  • Sorry for revisiting this late, but %c%d is expecting an input like a2 or z78 where %c part picks 'a' and %d part picks 2, or for z78 %c part picks up 'z' and %d part picks up 78. – Anurag Ambuj Jul 28 '23 at 09:12