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...

5
  • 5
    Newline is stored in buffer you pass to fgets.
    – TNW
    Commented Feb 2, 2016 at 21:51
  • Is there a solution to prevent this kind of behavior ?
    – Amin NAIRI
    Commented Feb 2, 2016 at 21:52
  • Yes. Remove the newline. You'll have to search for it and replace it with '\0'. Don't assume that there is a newline character in the string. Commented Feb 2, 2016 at 21:53
  • @Gradiuss: you have to trim out the \n from input Commented Feb 2, 2016 at 22:02
  • 1
    To trim, use stackoverflow.com/a/28462221/2410359 Commented Feb 3, 2016 at 2:02

1 Answer 1

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').

1
  • Thanks for adding the man, could you also suggest a correction ?
    – Amin NAIRI
    Commented Feb 2, 2016 at 22:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.