1

I tried to exercise with function in C as I managed to use a recursive function in C++ so here's my code :

#include <stdio.h>
#include <stdlib.h>

int Fctr(int n)
{
    return (n <= 1) ? 1 : n * Fctr(n -1);
}

int main(int argc, char** argv)
{
    char s_n[100];
    int i_n;

    printf("Factorial to calculate : ");
    fgets(s_n, 100, stdin);

    i_n = atoi(s_n);

    printf("The factorial of %s is equal to %d\n",s_n, Fctr(i_n));

    return 0;
}

Weird thing is that the output is the following :

Factorial to calculate : 5
The factorial of 5
 is equal to : 120

I compiled using GCC 5.3.0 with the following command :

gcc -o main main.c && ./main

I didn't even typed a \n between %s and the rest of my code. What's wrong with my second printf() ? I tried using %c instead of %s even tho it's a bad idea and it was indeed...

Amin NAIRI
  • 2,292
  • 21
  • 20

1 Answers1

4

Excerpt from man fgets on my PC:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

That's what happens. You'll have to check for newline and remove it on your own, preferably replacing it with ASCII NUL (0, or '\0').

TNW
  • 716
  • 6
  • 15