0

So I'm learning about forks and decided to do this program as a practice but it's executing scan twice (the program waits for a second input which basically does nothing!)

int n;
printf("Enter a number: ");
scanf("%d\n",&n);
if(fork()){ //p1

    wait(NULL);
    printf("Finished displaying factorial and summation\n");
    
}else if(fork()){ //p2
    
    wait(NULL);
    long fact=1;
    for(int j=1; j<=n; j++)
        fact*=j;
    printf("factorial of %d: %ld\n",n,fact);
    
}else{  //p3

    int sum=0;
    for(int i=1; i<=n;i++)
        sum +=i;
    printf("summation: %d\n",sum);
    
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Moe I.
  • 33
  • 8
  • I am not sure what you mean by "executing scan twice" – SergeyA Jul 14 '21 at 19:20
  • @SergeyA He means it's waiting for `scanf()` input twice. – Barmar Jul 14 '21 at 19:20
  • Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). And lastly please learn how to create a [mcve], with emphasis on the *minimal* part. If you took your code and simplified it bit by bit then the `fork` calls would go away and you would be left with the `scanf` call which would make that problem quite obvious. – Some programmer dude Jul 14 '21 at 19:23

1 Answers1

0

It's because the ending newline in the scanf format string.

That will causescanf to skip all and any white-space. But to figure out when the spaces ends, there must be some non-space input. So that leads to the second input.

Solution: Don't use trailing space of any kind in scanf format strings:

scanf("%d", &n);  // Note: No newline or any other space
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621